c#之AES加密解密
.Net已封装好算法,直接调用即可,代码如下:
转载请注明出处:https://www.cnblogs.com/jietian331/p/9707771.html
1 using System; 2 using System.Security.Cryptography; 3 using System.Text; 4 5 namespace AES 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 string str = "Hello world"; 12 string key = "12345678876543211234567887654abc"; 13 string result = AesEncrypt(str, key); 14 Console.WriteLine(result); 15 Console.WriteLine(AesDecrypt(result, key)); 16 Console.ReadKey(); 17 } 18 19 /// <summary> 20 /// AES 加密 21 /// </summary> 22 /// <param name="str">明文(待加密)</param> 23 /// <param name="key">密文</param> 24 /// <returns></returns> 25 public static string AesEncrypt(string str, string key) 26 { 27 if (string.IsNullOrEmpty(str)) 28 return null; 29 Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); 30 31 RijndaelManaged rm = new RijndaelManaged 32 { 33 Key = Encoding.UTF8.GetBytes(key), 34 Mode = CipherMode.ECB, 35 Padding = PaddingMode.PKCS7 36 }; 37 38 ICryptoTransform cTransform = rm.CreateEncryptor(); 39 Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 40 41 return Convert.ToBase64String(resultArray, 0, resultArray.Length); 42 } 43 /// <summary> 44 /// AES 解密 45 /// </summary> 46 /// <param name="str">明文(待解密)</param> 47 /// <param name="key">密文</param> 48 /// <returns></returns> 49 public static string AesDecrypt(string str, string key) 50 { 51 if (string.IsNullOrEmpty(str)) 52 return null; 53 Byte[] toEncryptArray = Convert.FromBase64String(str); 54 55 RijndaelManaged rm = new RijndaelManaged 56 { 57 Key = Encoding.UTF8.GetBytes(key), 58 Mode = CipherMode.ECB, 59 Padding = PaddingMode.PKCS7 60 }; 61 62 ICryptoTransform cTransform = rm.CreateDecryptor(); 63 Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 64 65 return Encoding.UTF8.GetString(resultArray); 66 } 67 } 68 }