1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
class AESHelper { /// <summary> /// AES加密(有向量) /// </summary> /// <param name="Data">被加密的明文</param> /// <param name="Key">密钥</param> /// <param name="IV">向量</param> /// <returns>密文</returns> public static string AESEncrypt(String Data, String Key,string IV) { MemoryStream mStream = new MemoryStream(); RijndaelManaged aes = new RijndaelManaged(); byte[] plainBytes = Encoding.UTF8.GetBytes(Data); byte[] bKey = System.Text.ASCIIEncoding.ASCII.GetBytes(Key); byte[] bIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; aes.Key = bKey; aes.IV = bIV; CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write); try { cryptoStream.Write(plainBytes, 0, plainBytes.Length); cryptoStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } finally { cryptoStream.Close(); mStream.Close(); aes.Clear(); } } /// <summary> /// AES解密(有向量) /// </summary> /// <param name="Data">被加密的明文</param> /// <param name="Key">密钥</param> /// <param name="IV">向量</param> /// <returns>明文</returns> public static string AESDecrypt(String Data, String Key,string IV) { Byte[] encryptedBytes = Convert.FromBase64String(Data); byte[] bKey = System.Text.ASCIIEncoding.ASCII.GetBytes(Key); byte[] bIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV); RijndaelManaged aes = new RijndaelManaged(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.BlockSize = 128; aes.KeySize = 128; aes.Key = bKey; aes.IV = bIV; MemoryStream mStream = new MemoryStream(encryptedBytes); CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read); try { //byte[] tmp = new byte[encryptedBytes.Length]; //int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length); //byte[] ret = new byte[len]; //Array.Copy(tmp, 0, ret, 0, len); //return Encoding.UTF8.GetString(ret); StreamReader sr = new StreamReader(cryptoStream); return sr.ReadToEnd(); } finally { cryptoStream.Close(); mStream.Close(); aes.Clear(); } } } |
转载请注明:二十画生 » C# AES加密解密