I am trying the most basic thing – encrypt data using the public key and decrypt using private key:
X509Certificate2 cert = new X509Certificate2(@"c:\temp\CERT\mycert.pfx", "test1");
RSACryptoServiceProvider privateKey = cert.PrivateKey as RSACryptoServiceProvider;
RSACryptoServiceProvider publicKey = cert.PublicKey.Key as RSACryptoServiceProvider;
UnicodeEncoding bytConvertor = new UnicodeEncoding();
byte[] plainData = bytConvertor.GetBytes("Sample data");
byte[] enData = publicKey.Encrypt(plainData, true);
Console.WriteLine("Encrypted Output: {0}", bytConvertor.GetString(enData));
byte[] deData = privateKey.Decrypt(enData, true);
Console.WriteLine("Decrypted Output: {0}", bytConvertor.GetString(deData));
But the 2nd last line privateKey.Decrypt(…) throws the following exception:
System.Security.Cryptography.CryptographicException was unhandled
Message=Bad Key.Source=mscorlib StackTrace: at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey(SafeKeyHandle pKeyContext, Byte[] pbEncryptedKey, Int32 cbEncryptedKey, Boolean fOAEP, ObjectHandleOnStack ohRetDecryptedKey) at System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP) at ConsoleApplication4.Program.Main(String[] args) in `c:\users\kazia\documents\visual studio` `2010\Projects\ConsoleApplication4\Program.cs`:line 44 ...InnerException:
I must be missing something obvious. What is the standard way to use RSA encryption in both end (public and private) using .NET? Any help would be appreciated.
Thanks!
Found the answer here:
http://msdn.microsoft.com/en-us/library/ms148409.aspx
Great example: