- A+
所属分类:.NET技术
最近在做调用第三方接口,要求入参AES加密,并且秘钥为16位的长度,在此记录一下。
首先引用命名空间:
using System.IO;
using System.Text;
using System.Security.Cryptography;
1 /// <summary> 2 /// AES加密(无向量) 3 /// </summary> 4 /// <param name="plainBytes">被加密的明文</param> 5 /// <param name="key">密钥</param> 6 /// <returns>密文</returns> 7 public string AESEncrypt(string Data, string Key) 8 { 9 MemoryStream mStream = new MemoryStream(); 10 RijndaelManaged aes = new RijndaelManaged(); 11 12 byte[] plainBytes = Encoding.UTF8.GetBytes(Data); 13 Byte[] bKey = new Byte[16]; 14 Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); 15 16 aes.Mode = CipherMode.ECB; 17 aes.Padding = PaddingMode.PKCS7; 18 aes.KeySize = 128; 19 //aes.Key = _key; 20 aes.Key = bKey; 21 //aes.IV = _iV; 22 CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write); 23 try 24 { 25 cryptoStream.Write(plainBytes, 0, plainBytes.Length); 26 cryptoStream.FlushFinalBlock(); 27 return Convert.ToBase64String(mStream.ToArray()); 28 } 29 finally 30 { 31 cryptoStream.Close(); 32 mStream.Close(); 33 aes.Clear(); 34 } 35 }
1 #region 解密 2 /// <summary> 3 /// AES解密(无向量) 4 /// </summary> 5 /// <param name="encryptedBytes">被加密的明文</param> 6 /// <param name="key">密钥</param> 7 /// <returns>明文</returns> 8 public string AESDecrypt(String Data, String Key) 9 { 10 Byte[] encryptedBytes = Convert.FromBase64String(Data); 11 Byte[] bKey = new Byte[16]; 12 Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); 13 14 MemoryStream mStream = new MemoryStream(encryptedBytes); 15 //mStream.Write( encryptedBytes, 0, encryptedBytes.Length ); 16 //mStream.Seek( 0, SeekOrigin.Begin ); 17 RijndaelManaged aes = new RijndaelManaged(); 18 aes.Mode = CipherMode.ECB; 19 aes.Padding = PaddingMode.PKCS7; 20 aes.KeySize = 128; 21 aes.Key = bKey; 22 //aes.IV = _iV; 23 CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read); 24 try 25 { 26 byte[] tmp = new byte[encryptedBytes.Length + 32]; 27 int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32); 28 byte[] ret = new byte[len]; 29 Array.Copy(tmp, 0, ret, 0, len); 30 return Encoding.UTF8.GetString(ret); 31 } 32 finally 33 { 34 cryptoStream.Close(); 35 mStream.Close(); 36 aes.Clear(); 37 } 38 } 39 #endregion
调用时:string sendData = publicSH.AESDecrypt(sendData, "HYYSIENDEUFHVKDA");//返回信息解密 sendData 为要加密或者解密的信息 ,第二个参数是16位的秘钥