I got a digital certificate from a certified body, with it I got a usb sticker with a private key. In VisualStudio I make Console application, i want to test the encryption and decryption with that certificate. For this I used already well known code:
private static string EncryptRSA(string input)
{
string outputMessage = String.Empty;
X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");
using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PublicKey.Key)
{
byte[] byteData = Encoding.UTF8.GetBytes(input);
byte[] byteEncrypted = csp.Encrypt(byteData, false);
outputMessage = Convert.ToBase64String(byteEncrypted);
}
return izlaznaPoruka;
}
public static string DecryptRsa(string enkriptovan)
{
string text = string.Empty;
X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");
using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PrivateKey)
{
byte[] byteEncrypted = Convert.FromBase64String(enkriptovan);
byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);
text = Encoding.UTF8.GetString(byteDecrypted);
}
return text;
}
Everything goes as it should until this moment, in the method DecryptRsa:
byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);
At this point, my authentication client requires a password - I enter the correct password, and the following exception pops up for me: An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll An internal error occurred.
Can any one help me?
I've researched a lot of solutions, but most private keys are exported to a .pfx file and use a three-parameter X509Certificate2 constructor when like this
X509Certificate2 cert = new X509Certificate2("myhost.pfx", "pass",
X509KeyStorageFlags.MachineKeySet);
Then change the permission of the folder ProgramData\Microsoft\Crypto\RSA\MachineKeys I manually changed the folder rights..