加密key与解密key不是一个,而是一对
加密key与解密key是不能互相推导的,有密文,没有解密key也推导不出来原文
加密解密速度慢,但是安全性好
特点:
公开解密key,保证数据的安全传递
公开机密key,保证数据的不可抵赖
code:
/// <summary> /// 获取非对称的这对密钥 /// </summary> /// <returns></returns> public static KeyValuePair<string, string> GetKeyPair() { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); return new KeyValuePair<string, string>(RSA.ToXmlString(false), RSA.ToXmlString(true)); } /// <summary> /// 加密 /// </summary> /// <param name="content">内容</param> /// <param name="key">密钥</param> /// <returns></returns> public static string Encrypt(string content, string key) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSA.FromXmlString(key); UnicodeEncoding unicodeEncoding = new UnicodeEncoding(); byte[] DataToEncrypt = unicodeEncoding.GetBytes(content); byte[] resultBytes = RSA.Encrypt(DataToEncrypt, false); return Convert.ToBase64String(resultBytes); } /// <summary> /// 解密 内容加解密key /// </summary> /// <param name="content"></param> /// <param name="key"></param> /// <returns></returns> public static string Decryp(string content, string key) { byte[] DataToEncrypt = Convert.FromBase64String(content); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSA.FromXmlString(key); byte[] resultBytes = RSA.Decrypt(DataToEncrypt, false); return Encoding.UTF8.GetString(resultBytes); }
static void Main(string[] args) { //获得加密解密键值对 KeyValuePair<string, string> keyValuePair = ReaEncrypt.GetKeyPair(); //加密 string rsaEnl = ReaEncrypt.Encrypt("ok", keyValuePair.Key); //解密 string rsadDel = ReaEncrypt.Decryp(rsaEnl, keyValuePair.Value); Console.WriteLine("Hello World!"); }