I'm using the RSACryptoServiceProvider
to encrypt and decrypt simple strings and while it works with normal certificates, it's giving me some grief when it comes to smart cards.
Here is the code I'm using:
private X509Certificate2 _cert // this certificate is set early on in the program
private string Encrypt(string Data)
{
if (string.IsNullOrEmpty(Data)) return default(string);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_cert.PublicKey.Key;
return Convert.ToBase64String(((rsa.Encrypt(Encoding.Unicode.GetBytes(Data), true))));
}
private string Decrypt(string CipherText)
{
if (string.IsNullOrEmpty(CipherText)) return default(string);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_cert.PrivateKey;
return Encoding.Unicode.GetString(((rsa.Decrypt(Convert.FromBase64String(CipherText), true))));
}
It does decrypt successfully (no errors) but the encoding isn't correct. It's giving me results like
\u08d8黔㡉Ẑ༴쨳층器\u0888諬翉烽偪䚘螷퓰薑낯ꄯ鯪ꘇ台ᾨ鳞텟칆蘟マ⺁ൿ䤳譻宐Ṹ鉱㒎艴偃堎え뢈癘蚰૩�⸮賆슉ଞ맿댿䀵㓹摵�뼚⡨ቾ᳓낣쏀ꖌ엷ὦ楐豎⸌ꅑ뙳餱Ч鎋筧粅嚄罜칮嬒쐞ڮ묭泊䘐쫦⊗邀☇仇挃箍絁绺罽华⏓፦귪ﻳ咷믭鹺簽艉闼敹Ԓ嵯젨泪ꔤ狫ꆙ\uab41軧\n"
What's also interesting is no matter what I encrypt, the decrypted byte[]
length is always 256.
I know smart card private key operations always take place on the card itself so I'm sure that has something to do with it but I was hoping some of you have experience with this and can save me the mounds of trial-and-error.
Thanks!