1 public class AESEncryption 2 { 3 #region 加密 4 /// <summary> 5 /// 加密 6 /// </summary> 7 /// <param name="input">需要加密的字符串</param> 8 /// <param name="iv">向量</param> 9 /// <param name="key">密钥</param> 10 /// <returns>加密后base64编码字符串</returns> 11 public static String Encrypt(String input, String iv, String key) 12 { 13 Byte[] keyBytes = Convert.FromBase64String(key); 14 Byte[] ivBytes = Convert.FromBase64String(iv); 15 using (RijndaelManaged rm = new RijndaelManaged()) 16 { 17 rm.Key = keyBytes; 18 rm.IV = ivBytes; 19 ICryptoTransform encryptor = rm.CreateEncryptor(rm.Key, rm.IV); 20 using (MemoryStream msEncrypt = new MemoryStream()) 21 { 22 using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) 23 { 24 using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 25 { 26 swEncrypt.Write(input); 27 } 28 Byte[] encrypted = msEncrypt.ToArray(); 29 return Convert.ToBase64String(encrypted); 30 } 31 } 32 } 33 } 34 #endregion 35 36 #region 解密 37 /// <summary> 38 /// 解密 39 /// </summary> 40 /// <param name="input">需要解密的字符串</param> 41 /// <param name="iv">向量</param> 42 /// <param name="key">密钥</param> 43 /// <returns>加密之后的字符串</returns> 44 public static String Decrypt(String input, String iv, String key) 45 { 46 Byte[] inputBytes = Convert.FromBase64String(input); 47 Byte[] keyBytes = Convert.FromBase64String(key); 48 Byte[] ivBytes = Convert.FromBase64String(iv); 49 using (RijndaelManaged rm = new RijndaelManaged()) 50 { 51 rm.Key = keyBytes; 52 rm.IV = ivBytes; 53 ICryptoTransform decryptor = rm.CreateDecryptor(rm.Key, rm.IV); 54 using (MemoryStream msDecrypt = new MemoryStream(inputBytes)) 55 { 56 using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) 57 { 58 using (StreamReader srDecrypt = new StreamReader(csDecrypt)) 59 { 60 return srDecrypt.ReadToEnd(); 61 } 62 } 63 } 64 } 65 } 66 #endregion 67 }