"Bad key" exception for certificates with exportable private key
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 开发者_JS百科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?
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.
精彩评论