最近在做調用第三方介面,要求入參AES加密,並且秘鑰為16位的長度,在此記錄一下。 首先引用命名空間: using System.IO; using System.Text; using System.Security.Cryptography; 1 /// <summary> 2 /// AES加 ...
最近在做調用第三方介面,要求入參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位的秘鑰