using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Common { /// /// AES加密 /// 创建人:赵耀 /// 创建时间:2020年9月7日 /// public class AESHelper { public static string QrcodeLoginKey = "zyyxhlywkdatakey"; /// /// AES 加密 /// /// Need encrypted string /// Encrypted 16 hex string public static string AESEncrypt(String Data) { string key = QrcodeLoginKey.PadRight(16, '0'); // 256-AES key byte[] keyArray = UTF8Encoding.ASCII.GetBytes(key); byte[] toEncryptArray = UTF8Encoding.ASCII.GetBytes(Data); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return BytesToHexString(resultArray); } /// /// AES 解密 /// /// Encrypted 16 hex string /// Decrypted string public static string AESDecrypt(String hexString) { string key = QrcodeLoginKey.PadRight(16, '0'); // 256-AES key byte[] keyArray = UTF8Encoding.ASCII.GetBytes(key); byte[] toEncryptArray = HexStringToBytes(hexString); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return UTF8Encoding.ASCII.GetString(resultArray); } /// /// Byte array to convert 16 hex string /// /// byte array /// 16 hex string public static string BytesToHexString(byte[] bytes) { StringBuilder returnStr = new StringBuilder(); if (bytes != null || bytes.Length == 0) { for (int i = 0; i < bytes.Length; i++) { returnStr.Append(bytes[i].ToString("X2")); } } return returnStr.ToString(); } /// /// 16 hex string converted to byte array /// /// 16 hex string /// byte array public static byte[] HexStringToBytes(String hexString) { if (hexString == null || hexString.Equals("")) { return null; } int length = hexString.Length / 2; if (hexString.Length % 2 != 0) { return null; } byte[] d = new byte[length]; for (int i = 0; i < length; i++) { d[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); } return d; } } }