1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Security.Cryptography; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace MyEncrypt 10 { 11 /// <summary> 12 /// RSA ECC 13 /// 可逆非对称加密 14 /// 非对称加密算法的优点是密钥管理很方便,缺点是速度慢。 15 /// </summary> 16 public class RsaEncrypt 17 { 18 19 /// <summary> 20 /// 获取加密/解密对 21 /// Encrypt Decrypt 22 /// </summary> 23 /// <returns>Encrypt Decrypt</returns> 24 public static KeyValuePair<string, string> GetKeyPair() 25 { 26 RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); 27 string publicKey = RSA.ToXmlString(false); 28 string privateKey = RSA.ToXmlString(true); 29 return new KeyValuePair<string, string>(publicKey, privateKey); 30 } 31 32 /// <summary> 33 /// 加密:内容+加密key 34 /// </summary> 35 /// <param name="content"></param> 36 /// <param name="encryptKey">加密key</param> 37 /// <returns></returns> 38 public static string Encrypt(string content, string encryptKey) 39 { 40 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); 41 rsa.FromXmlString(encryptKey); 42 UnicodeEncoding ByteConverter = new UnicodeEncoding(); 43 byte[] DataToEncrypt = ByteConverter.GetBytes(content); 44 byte[] resultBytes = rsa.Encrypt(DataToEncrypt, false); 45 return Convert.ToBase64String(resultBytes); 46 } 47 48 /// <summary> 49 /// 解密 内容+解密key 50 /// </summary> 51 /// <param name="content"></param> 52 /// <param name="decryptKey">解密key</param> 53 /// <returns></returns> 54 public static string Decrypt(string content, string decryptKey) 55 { 56 byte[] dataToDecrypt = Convert.FromBase64String(content); 57 RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); 58 RSA.FromXmlString(decryptKey); 59 byte[] resultBytes = RSA.Decrypt(dataToDecrypt, false); 60 UnicodeEncoding ByteConverter = new UnicodeEncoding(); 61 return ByteConverter.GetString(resultBytes); 62 } 63 64 65 /// <summary> 66 /// 可以合并在一起的,,每次产生一组新的密钥 67 /// </summary> 68 /// <param name="content"></param> 69 /// <param name="encryptKey">加密key</param> 70 /// <param name="decryptKey">解密key</param> 71 /// <returns>加密后结果</returns> 72 private static string Encrypt(string content, out string publicKey, out string privateKey) 73 { 74 RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(); 75 publicKey = rsaProvider.ToXmlString(false); 76 privateKey = rsaProvider.ToXmlString(true); 77 78 UnicodeEncoding ByteConverter = new UnicodeEncoding(); 79 byte[] DataToEncrypt = ByteConverter.GetBytes(content); 80 byte[] resultBytes = rsaProvider.Encrypt(DataToEncrypt, false); 81 return Convert.ToBase64String(resultBytes); 82 } 83 } 84 }