C#使用RSA加密算法重要的一个类就是RSACryptoServiceProvider,这个类可以生成一对公钥和私钥,同时也可以加密和解密。
生成privatekey代码:
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); var privatekey=rsa.ToXmlString(true);
生成publickey代码:
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); var publickey=rsa.ToXmlString(false);
完整Helper帮助类代码:
public class RSAEncryption { public static readonly string publickey = @"生成的publickey"; public static readonly string privatekey = @"生成的privatekey"; /// <summary> /// RSA加密 /// </summary> /// <param name="publickey"></param> /// <param name="content"></param> /// <returns></returns> public static string RSAEncrypt(string content) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(publickey); cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherbytes); } /// <summary> /// RSA解密 /// </summary> /// <param name="privatekey"></param> /// <param name="content"></param> /// <returns></returns> public static bool RSADecrypt(string content, out string rslt) { try { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(privatekey); cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false); rslt = Encoding.UTF8.GetString(cipherbytes); return true; } catch (System.Security.Cryptography.CryptographicException e1) { rslt = ""; return false; } } }
转载请说明出处:博客微站原文链接: