using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace MV485.util { public class AesEncryptionHelper { // 定义一个静态的密钥和初始化向量(IV),这两个值应该保密并且保持不变。 //private static readonly byte[] Key = Encoding.UTF8.GetBytes("Your16ByteKeyHere!"); // 16, 24, or 32 bytes for AES-128, AES-192, or AES-256 //private static readonly byte[] IV = Encoding.UTF8.GetBytes("Your16ByteIVHere!"); // 必须是16字节 public static string key = "bjhcxd@aitest$tool!s"; // 密钥可以是任意长度,但会自动填充到 32 字节 // AES 加密方法 public static string EncryptString(string plainText, string key) { using (Aes aesAlg = Aes.Create()) { // 设置密钥和生成随机的 IV byte[] keyBytes = Encoding.UTF8.GetBytes(key.PadRight(32, '0').Substring(0, 32)); // 确保密钥长度为 32 字节 aesAlg.Key = keyBytes; aesAlg.GenerateIV(); // 生成随机的 IV // 创建加密器 ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // 将明文转换为字节数组 byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // 使用内存流进行加密 using (MemoryStream msEncrypt = new MemoryStream()) { // 写入 IV 到输出流 msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); // 使用加密器加密数据 using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } // 返回加密后的数据作为 Base64 字符串 return Convert.ToBase64String(msEncrypt.ToArray()); } } } // AES 解密方法 public static string DecryptString(string cipherText, string key) { using (Aes aesAlg = Aes.Create()) { // 设置密钥 byte[] keyBytes = Encoding.UTF8.GetBytes(key.PadRight(32, '0').Substring(0, 32)); // 确保密钥长度为 32 字节 aesAlg.Key = keyBytes; // 将 Base64 编码的密文转换为字节数组 byte[] cipherTextBytes = Convert.FromBase64String(cipherText); // 从密文中提取 IV int ivLength = BitConverter.ToInt32(cipherTextBytes, 0); byte[] iv = new byte[ivLength]; Array.Copy(cipherTextBytes, sizeof(int), iv, 0, ivLength); aesAlg.IV = iv; // 创建解密器 ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // 使用内存流进行解密 using (MemoryStream msDecrypt = new MemoryStream(cipherTextBytes, sizeof(int) + ivLength, cipherTextBytes.Length - sizeof(int) - ivLength)) using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // 返回解密后的字符串 return srDecrypt.ReadToEnd(); } } } //----------------------------------------------------------------------------- } }