Simple use of RSACryptoServiceProvider KeyPassword fails

江枫思渺然 提交于 2019-12-14 02:06:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/1915797/simple-use-of-rsacryptoserviceprovider-keypassword-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!