using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; namespace LSServerService { /// /// AES对称加密 /// public class AESUtil { private static string key = "lserpasebygyc222"; #region AES加解密 /// ///AES加密(加密步骤) ///1,加密字符串得到2进制数组; ///2,将2进制数组转为16进制; ///3,进行base64编码 /// /// 要加密的字符串 /// 密钥 public static string Encrypt(string toEncrypt) { if (string.IsNullOrEmpty(toEncrypt)) return ""; byte[] _key = Encoding.ASCII.GetBytes(key); byte[] _source = Encoding.UTF8.GetBytes(toEncrypt); Aes aes = Aes.Create("AES"); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; aes.Key = _key; ICryptoTransform cTransform = aes.CreateEncryptor(); byte[] cryptData = cTransform.TransformFinalBlock(_source, 0, _source.Length); string hexCryptString = Hex_2To16(cryptData); byte[] hexCryptData = Encoding.UTF8.GetBytes(hexCryptString); return Convert.ToBase64String(hexCryptData); } /// /// AES解密(解密步骤) /// 1,将BASE64字符串转为16进制数组 /// 2,将16进制数组转为字符串 /// 3,将字符串转为2进制数据 /// 4,用AES解密数据 /// /// 已加密的内容 /// 密钥 public static string Decrypt(string toDecrypt) { if (string.IsNullOrEmpty(toDecrypt)) return ""; try { byte[] _key = Encoding.ASCII.GetBytes(key); Aes aes = Aes.Create("AES"); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; aes.Key = _key; ICryptoTransform cTransform = aes.CreateDecryptor(); byte[] encryptedData = Convert.FromBase64String(toDecrypt); string encryptedString = Encoding.UTF8.GetString(encryptedData); byte[] _source = Hex_16To2(encryptedString); byte[] originalSrouceData = cTransform.TransformFinalBlock(_source, 0, _source.Length); return Encoding.UTF8.GetString(originalSrouceData); } catch (Exception) { return ""; } } /// /// 2进制转16进制 /// static string Hex_2To16(byte[] bytes) { string hexString = string.Empty; Int32 iLength = 65535; if (bytes != null) { StringBuilder strB = new StringBuilder(); if (bytes.Length < iLength) { iLength = bytes.Length; } for (int i = 0; i < iLength; i++) { strB.Append(bytes[i].ToString("X2")); } hexString = strB.ToString(); } return hexString; } /// /// 16进制转2进制 /// static byte[] Hex_16To2(string hexString) { if ((hexString.Length % 2) != 0) { hexString += " "; } byte[] returnBytes = new Byte[hexString.Length / 2]; for (Int32 i = 0; i < returnBytes.Length; i++) { returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); } return returnBytes; } #endregion } }