Skip to content

Instantly share code, notes, and snippets.

@samjgriffin89
Created June 26, 2015 19:04
Show Gist options
  • Save samjgriffin89/22d2ab13ec9403614468 to your computer and use it in GitHub Desktop.
Save samjgriffin89/22d2ab13ec9403614468 to your computer and use it in GitHub Desktop.
RSA Encryption/Decryption with X509 Certificates
private X509Certificate2 RsaCertificate
{
get
{
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, ConfigurationManager.AppSettings.Get("CertificateSubjectName"), false);
store.Close();
return certs[0];
}
}
/// <summary>
/// Encrypt a string using RSA algorithm.
/// </summary>
/// <param name="stringToEncrypt"></param>
/// <returns>Base-64 string encrypted string</returns>
public string RsaEncrypt(string stringToEncrypt)
{
var dataToEncrypt = Encoding.UTF8.GetBytes(stringToEncrypt);
using (var rsa = (RSACryptoServiceProvider)RsaCertificate.PublicKey.Key)
{
var encryptedData = rsa.Encrypt(dataToEncrypt, false);
return Convert.ToBase64String(encryptedData);
}
}
/// <summary>
/// Decrypt a string in base-64 format based on the RSA algorithm
/// </summary>
/// <param name="stringToDecrypt"></param>
/// <returns>Originally encrypted string</returns>
public string RsaDecrypt(string stringToDecrypt)
{
var dataToDecrypt = Convert.FromBase64String(stringToDecrypt);
using (var rsa = (RSACryptoServiceProvider)RsaCertificate.PrivateKey)
{
var decrytpedData = rsa.Decrypt(dataToDecrypt, false);
return Encoding.UTF8.GetString(decrytpedData);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment