using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Container.Common { /// /// 加密解密类 /// public class SecurityHelper { #region AES加密解密 private static App app = ((App)System.Windows.Application.Current); /// /// 128位处理key /// /// 原字节 /// 处理key /// private static byte[] GetAesKey(byte[] keyArray, string key) { byte[] newArray = new byte[16]; if (keyArray.Length < 16) { for (int i = 0; i < newArray.Length; i++) { if (i >= keyArray.Length) { newArray[i] = 0; } else { newArray[i] = keyArray[i]; } } } else newArray = keyArray; return newArray; } /// /// 使用AES加密字符串,按128位处理key /// /// 加密内容 /// 秘钥,需要128位、256位..... /// Base64字符串结果 public static string AesEncrypt(string content, bool autoHandle = true) { byte[] keyArray = Encoding.UTF8.GetBytes(app.SecurityKey); if (autoHandle) { keyArray = GetAesKey(keyArray, app.SecurityKey); } byte[] toEncryptArray = Encoding.UTF8.GetBytes(content); SymmetricAlgorithm des = Aes.Create(); des.Key = keyArray; des.Mode = CipherMode.ECB; des.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = des.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray); } /// /// 使用AES解密字符串,按128位处理key /// /// 内容 /// 秘钥,需要128位、256位..... /// UTF8解密结果 public static string AesDecrypt(string content, bool autoHandle = true) { byte[] keyArray = Encoding.UTF8.GetBytes(app.SecurityKey); if (autoHandle) { keyArray = GetAesKey(keyArray, app.SecurityKey); } byte[] toEncryptArray = Convert.FromBase64String(content); SymmetricAlgorithm des = Aes.Create(); des.Key = keyArray; des.Mode = CipherMode.ECB; des.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = des.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } #endregion } }