.Net AES加密与解密
作者:互联网
/// <summary> /// AES加密 /// </summary> /// <param name="Data">被加密的明文</param> /// <param name="Key">密钥</param> /// <param name="Vector">向量</param> /// <returns>密文</returns> public static String AESEncrypt(String Data, String Key, String Vector) { Byte[] plainBytes = Encoding.UTF8.GetBytes(Data); byte[] bKey = Encoding.ASCII.GetBytes(Key); byte[] bVector = Encoding.ASCII.GetBytes(Vector); Byte[] Cryptograph = null; // 加密后的密文 Rijndael Aes = Rijndael.Create(); try { // 开辟一块内存流 using (MemoryStream Memory = new MemoryStream()) { // 把内存流对象包装成加密流对象 using (CryptoStream Encryptor = new CryptoStream(Memory, Aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write)) { // 明文数据写入加密流 Encryptor.Write(plainBytes, 0, plainBytes.Length); Encryptor.FlushFinalBlock(); Cryptograph = Memory.ToArray(); } } } catch { Cryptograph = null; } return Convert.ToBase64String(Cryptograph).Replace("/", "_").Replace("+", "-"); } /// <summary> /// AES解密 /// </summary> /// <param name="Data">被解密的密文</param> /// <param name="Key">密钥</param> /// <param name="Vector">向量</param> /// <returns>明文</returns> public static String AESDecrypt(String Data, String Key, String Vector) { Data = Data.Replace("_", "/").Replace("-", "+"); Byte[] encryptedBytes = Convert.FromBase64String(Data); byte[] bKey = Encoding.ASCII.GetBytes(Key); byte[] bVector = Encoding.ASCII.GetBytes(Vector); Byte[] original = null; // 解密后的明文 Rijndael Aes = Rijndael.Create(); try { // 开辟一块内存流,存储密文 using (MemoryStream Memory = new MemoryStream(encryptedBytes)) { // 把内存流对象包装成加密流对象 using (CryptoStream Decryptor = new CryptoStream(Memory, Aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read)) { // 明文存储区 using (MemoryStream originalMemory = new MemoryStream()) { Byte[] Buffer = new Byte[1024]; Int32 readBytes = 0; while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0) { originalMemory.Write(Buffer, 0, readBytes); } original = originalMemory.ToArray(); } } } } catch (Exception ex) { original = null; } return Encoding.UTF8.GetString(original); }
标签:AES,String,Encoding,解密,new,Net,Data,Byte,MemoryStream 来源: https://www.cnblogs.com/leileichina/p/16309047.html