2011年6月14日 星期二

Certificate Encryption/Decryption Example on C#

The following are example functions using a PKCS12 cert. (It has both public and private keys) and the result is encoded/decoded by base64.

static string Decrypt(string data)
{
X509Certificate2 myCertificate = new X509Certificate2("c:\\temp\\mycerts.p12","123456");
RSACryptoServiceProvider provider1 = (RSACryptoServiceProvider)myCertificate.PrivateKey;
byte[] buffer1 = Convert.FromBase64String(data);
byte[] result = provider1.Decrypt(buffer1,false);
return Encoding.UTF8.GetString(result);
//return (new UnicodeEncoding()).GetString(result);
}
static string Encrypt(string data)
{
X509Certificate2 myCertificate = new X509Certificate2("c:\\temp\\mycerts.p12", "123456");
RSACryptoServiceProvider provider1 = (RSACryptoServiceProvider)myCertificate.PublicKey.Key;
//byte[] buffer1 = (new UnicodeEncoding()).GetBytes(data);
byte[] buffer1 = Encoding.UTF8.GetBytes(data);
byte[] result = provider1.Encrypt(buffer1,
false);
string b64s = Convert.ToBase64String(result);
return b64s;
}

static bool VerifyData(string data, string signature)
{
X509Certificate2 myCertificate = new X509Certificate2("c:\\temp\\mycerts.p12", "123456");
RSACryptoServiceProvider provider1 = (RSACryptoServiceProvider)myCertificate.PublicKey.Key;
byte[] sb = Convert.FromBase64String(signature);
//byte[] db = (new ASCIIEncoding()).GetBytes(data);
byte[] db = Encoding.UTF8.GetBytes(data);
return provider1.VerifyData(db, new SHA1CryptoServiceProvider(
), sb);
}

static string SignData(string data)
{
X509Certificate2 myCertificate = new X509Certificate2("c:\\temp\\mycerts.p12", "123456");
RSACryptoServiceProvider provider1 = (RSACryptoServiceProvider)myCertificate.PrivateKey;
//byte[] db = (new ASCIIEncoding()).GetBytes(data);
byte[] db = Encoding.UTF8.GetBytes(data);
byte[] sb = provider1.SignData(db, new SHA1CryptoServiceProvider(
));
return Convert.ToBase64String(sb);
}

沒有留言: