一、RSA加密简介
RSA加密是一种非对称加密。可以在不直接传递密钥的情况下,完成解密。这能够确保信息的安全性,避免了直接传递密钥所造成的被破解的风险。是由一对密钥来进行加解密的过程,分别称为公钥和私钥。通常个人保存私钥,公钥是公开的。
二、RSA加密流程如下
1.系统生成一对密钥(公钥和私钥)
2.系统将公钥告知客户
3.客户根据收到的公钥对数据进行加密,在发送给系统
4.系统收到加密后的数据,用私钥进行解密
1 public class RSA 2 { 3 /// <summary> 4 /// 生成密钥 5 /// </summary> 6 /// <param name="PrivateKey">私钥</param> 7 /// <param name="PublicKey">公钥</param> 8 /// <param name="KeySize">密钥长度512,1024,2048,4096</param> 9 public static void Generate(out string PrivateKey, out string PublicKey, int KeySize = 2048) 10 { 11 //初始化加密对象,并且设置密钥的长度 12 RSACryptoServiceProvider serviceProvider = new RSACryptoServiceProvider(KeySize); 13 //false 表示仅包含公钥。 14 PublicKey = serviceProvider.ToXmlString(false); 15 //true 表示同时包含 RSA 公钥和私钥 16 PrivateKey = serviceProvider.ToXmlString(true); 17 } 18 /// <summary> 19 /// 加密 20 /// </summary> 21 /// <param name="PublicKey">公钥</param> 22 /// <param name="EncryptString">待加密字符串</param> 23 /// <returns></returns> 24 public static string RSAEncrypt(string PublicKey, string EncryptString) 25 { 26 byte[] inputByArray; 27 byte[] outPutByArray; 28 string result; 29 RSACryptoServiceProvider serviceProvider = new RSACryptoServiceProvider(); 30 serviceProvider.FromXmlString(PublicKey); 31 inputByArray = Encoding.UTF8.GetBytes(EncryptString); 32 outPutByArray = serviceProvider.Encrypt(inputByArray, false); 33 result = Convert.ToBase64String(outPutByArray); 34 return result; 35 } 36 /// <summary> 37 /// 解密 38 /// </summary> 39 /// <param name="PrivateKey">私钥</param> 40 /// <param name="DecryptString">待加密字符串</param> 41 /// <returns></returns> 42 public static string RSADecrypt(string PrivateKey, string DecryptString) 43 { 44 byte[] inputByArray; 45 byte[] outPutByArray; 46 string result; 47 RSACryptoServiceProvider serviceProvider = new RSACryptoServiceProvider(); 48 serviceProvider.FromXmlString(PrivateKey); 49 inputByArray = Convert.FromBase64String(DecryptString); 50 outPutByArray = serviceProvider.Decrypt(inputByArray, false); 51 result = Encoding.UTF8.GetString(outPutByArray); 52 return result; 53 } 54 55 }
1 static void Main(string[] args) 2 { 3 string PrivateKey; 4 string PublicKey; 5 RSA.Generate(out PrivateKey, out PublicKey); 6 Console.WriteLine("私钥的值:{0},公钥的值:{1}", PrivateKey, PublicKey); 7 var encryptResult = RSA.RSAEncrypt(PublicKey, "123456"); 8 var decryptResult = RSA.RSADecrypt(PrivateKey, encryptResult); 9 Console.WriteLine("加密后的值:{0},解密后的值:{1}", encryptResult, decryptResult); 10 }