1、RSA加密簡介安全
RSA加密是一種非對稱加密。能夠在不直接傳遞密鑰的狀況下,完成解密。這可以確保信息的安全性,避免了直接傳遞密鑰所形成的被破解的風險。是由一對密鑰來進行加解密的過程,分別稱爲公鑰和私鑰。一般我的保存私鑰,公鑰是公開的。ide
2、RSA加密流程以下加密
1.系統生成一對密鑰(公鑰和私鑰)spa
2.系統將公鑰告知客戶code
3.客戶根據收到的公鑰對數據進行加密,在發送給系統對象
4.系統收到加密後的數據,用私鑰進行解密blog
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 }