asp.net AES加密跟PHP的一致,将加密的2进制byte[]转换为16进制byte[] 的字符串获得
<?php class AESUtil { public static function encrypt($input, $key) { $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $input = AESUtil::pkcs5_pad($input, $size); $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND); mcrypt_generic_init($td, $key, $iv); $data = mcrypt_generic($td, $input); mcrypt_generic_deinit($td); mcrypt_module_close($td); $data = strtoupper(bin2hex($data)); return $data; } private static function pkcs5_pad ($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } public static function decrypt($sStr, $sKey) { $decrypted= mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $sKey, base64_decode($sStr), MCRYPT_MODE_ECB ); $dec_s = strlen($decrypted); $padding = ord($decrypted[$dec_s-1]); $decrypted = substr($decrypted, 0, -$padding); return $decrypted; } } ?>
下面这个跟PHP的一样加密后,将加密的2进制byte[]转换为16进制byte[] 的字符串获得
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; namespace pay { class AESHelper { /// <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 = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); Byte[] bVector = new Byte[16]; Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length); 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); } /// <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) { Byte[] encryptedBytes = Convert.FromBase64String(Data); Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); Byte[] bVector = new Byte[16]; Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length); 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 { original = null; } return Encoding.UTF8.GetString(original); } /// <summary> /// AES加密(无向量) /// </summary> /// <param name="plainBytes">被加密的明文</param> /// <param name="key">密钥</param> /// <returns>密文</returns> public static string AESEncrypt(String Data, String Key) { MemoryStream mStream = new MemoryStream(); RijndaelManaged aes = new RijndaelManaged(); byte[] plainBytes = Encoding.UTF8.GetBytes(Data); Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; // aes.Key = bKey; aes.IV = Encoding.UTF8.GetBytes(Key); CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write); try { cryptoStream.Write(plainBytes, 0, plainBytes.Length); cryptoStream.FlushFinalBlock(); byte[] hs = mStream.ToArray(); StringBuilder sb = new StringBuilder(); foreach (byte b in hs) { // 以十六进制格式格式化 sb.Append(b.ToString("X2")); } return sb.ToString(); // return Convert.ToBase64String(mStream.ToArray()); //Byte[] mStream.ToArray(); //System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); //String StringMessage = UTF8.GetString(mStream.ToArray()); //return StringMessage; } finally { cryptoStream.Close(); mStream.Close(); aes.Clear(); } } /// <summary> /// AES解密(无向量) /// </summary> /// <param name="encryptedBytes">被加密的明文</param> /// <param name="key">密钥</param> /// <returns>明文</returns> public static string AESDecrypt(String Data, String Key) { Byte[] encryptedBytes = Convert.FromBase64String(Data); Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); MemoryStream mStream = new MemoryStream(encryptedBytes); //mStream.Write( encryptedBytes, 0, encryptedBytes.Length ); //mStream.Seek( 0, SeekOrigin.Begin ); RijndaelManaged aes = new RijndaelManaged(); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; aes.Key = bKey; // aes.IV = _iV; CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read); try { byte[] tmp = new byte[encryptedBytes.Length + 32]; int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32); byte[] ret = new byte[len]; Array.Copy(tmp, 0, ret, 0, len); return Encoding.UTF8.GetString(ret); } finally { cryptoStream.Close(); mStream.Close(); aes.Clear(); } } //下面这一个才能对应上面的PHP版AES加密 /// <summary> /// AES加密 /// </summary> /// <param name="str">要加密字符串</param> /// <returns>返回加密后字符串</returns> public static String Encrypt_AES(String str,String key) { Byte[] keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(key); Byte[] toEncryptArray = System.Text.UTF8Encoding.UTF8.GetBytes(str); System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = System.Security.Cryptography.CipherMode.ECB; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); byte[] hs = resultArray; StringBuilder sb = new StringBuilder(); foreach (byte b in hs) { // 以十六进制格式格式化 sb.Append(b.ToString("X2")); } return sb.ToString(); } /// <summary> /// AES解密 /// </summary> /// <param name="str">要解密字符串</param> /// <returns>返回解密后字符串</returns> public static String Decrypt_AES(String str) { Byte[] keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(strAesKey); Byte[] toEncryptArray = Convert.FromBase64String(str); System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = System.Security.Cryptography.CipherMode.ECB; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return System.Text.UTF8Encoding.UTF8.GetString(resultArray); } } }
解密的时候如果不成功,其实要把16进制密文转成字节
字符串转16进制字节数组 /// <summary> /// 字符串转16进制字节数组 /// </summary> /// <param name="hexString"></param> /// <returns></returns> private static byte[] strToToHexByte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; }
然后在进行解密
/// <summary> /// AES解密 /// </summary> /// <param name="str">要解密字符串</param> /// <returns>返回解密后字符串</returns> public static String Decrypt_AES(String str, string strAesKey,Byte[] strbyte) { Byte[] keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(strAesKey); Byte[] toEncryptArray =Convert.FromBase64String(str); if (str+""=="") { toEncryptArray = strbyte; } //Byte[] toEncryptArray = System.Text.UTF8Encoding.UTF8.GetBytes(str); System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = System.Security.Cryptography.CipherMode.ECB; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return System.Text.UTF8Encoding.UTF8.GetString(resultArray); }