“Bad key” exception for certificates with exportable private key

╄→尐↘猪︶ㄣ 提交于 2019-12-21 07:15:09

问题


I am trying to encrypt and then decrypt files using asymmetric encryption. I've created a test certificate using makecert and installed it into my personal localmachine store. In future I'll have to install this certificate on several servers, that's why I've created it with "-pe" flag, that is, with exportable private key. The certificates has been successfully created and installed, I see the "You have a private key that corresponds to this certificate" note in mmc.

Now I am trying to encrypt data with RSACryptoServiceProvider in .NET 3.5. And it succeeds. But when I am trying to decrypt it, I get "Bad key" exception.

If I create the certificate without "-pe" option, the same code works well for decryption. Here is the code:

RSA rsaKey = (RSA)myCertificate.PrivateKey;
RSACryptoServiceProvider rsaCsp = (RSACryptoServiceProvider)rsaKey;
byte[] plainText = rsaCsp.Decrypt(encryptedText, true);

Also I've tried another method, using System.Security.Cryptography.Pkcs namespace:

EnvelopedCms envelope = new EnvelopedCms();
envelope.Decode(encryptedText);
envelope.Decrypt();
byte[] plainText = envelope.ContentInfo.Content;

The result was the same... Can anyone help?


回答1:


Ensure that the key you're using was created with "-sky Exchange" if using makecert.exe. Without this, you can only use the key for signing and authentication, not encryption/decryption which is the use case you're implementing here.



来源:https://stackoverflow.com/questions/2037072/bad-key-exception-for-certificates-with-exportable-private-key

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