开发者

Simple use of RSACryptoServiceProvider KeyPassword fails

开发者 https://www.devze.com 2022-12-14 08:40 出处:网络
I want to protect my RSA private key with a password (who wouldn\'t) but the following C# fails: SecureString pw = new SecureString();

I want to protect my RSA private key with a password (who wouldn't) but the following C# fails:

SecureString pw = new SecureString();
pw.AppendChar('x');
CspParameters prms = new CspParameters();
prms.KeyPassword = pw;
RSACryptoServiceProvider crypto = new RSACryptoServiceProvider(prms);
byte[] encrypted = crypto.Encrypt(Encoding.ASCII开发者_如何转开发.GetBytes("encryptme"), true);

...with the CryptographicException: "Invalid type specified". If I take the KeyPassword assignment out it works fine.

What am I, or Microsoft, doing wrong?


Setting CspParameters.KeyPassword is equivalent to calling CryptSetProvParam with PP_KEYEXCHANGE_PIN (or PP_SIGNATURE_PIN). This flag is not supported by the default Microsoft crypto-service-provider (it is intended for use with smartcard-based CSPs).

You might want to try setting

prms.Flags = CspProviderFlags.UseUserProtectedKey;

or alternatively generating a non-persistent key-pair, exporting it and encrypting it with a key derived from a password yourself.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号