using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.Intrinsics.X86; using System.Security.Cryptography; using System.Text; namespace SunlightAggregationManager.UserClass { public class AES { public static string AesEncipher(string Key, string dat) //加密 { //压缩 byte[] plainBytes = Compress( Encoding.UTF8.GetBytes(dat)); using var sha256 = System.Security.Cryptography.SHA256.Create(); using var aes = System.Security.Cryptography.Aes.Create(); aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Key)); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.GenerateIV(); // 生成随机 IV using var enc = aes.CreateEncryptor(); byte[] cipherBytes = enc.TransformFinalBlock(plainBytes, 0, plainBytes.Length); //将 IV (16字节) 和 密文 拼接成一个完整的字节数组 byte[] combinedBytes = new byte[aes.IV.Length + cipherBytes.Length]; Buffer.BlockCopy(aes.IV, 0, combinedBytes, 0, aes.IV.Length); Buffer.BlockCopy(cipherBytes, 0, combinedBytes, aes.IV.Length, cipherBytes.Length); return Convert.ToBase64String(combinedBytes); } public static string AesDecrypt(string Key, string dat)//解密 { // 解码Base64 byte[] cipherBytes = Convert.FromBase64String(dat); using var sha256 = System.Security.Cryptography.SHA256.Create(); using var aes = System.Security.Cryptography.Aes.Create(); aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Key)); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; // 从字节数组中提取前 16 字节作为 IV aes.IV = cipherBytes.AsSpan(0, 16).ToArray(); using var dec = aes.CreateDecryptor(); // 解密 byte[] bytes = dec.TransformFinalBlock(cipherBytes, 16, cipherBytes.Length - 16); //解压缩并返回 return Encoding.UTF8.GetString(Decompress(bytes)); } // 3. Brotli 压缩辅助方法 private static byte[] Compress(byte[] data) { using var output = new MemoryStream(); using (var brotli = new BrotliStream(output, CompressionLevel.Optimal)) { brotli.Write(data, 0, data.Length); } return output.ToArray(); } // 4. Brotli 解压辅助方法 private static byte[] Decompress(byte[] data) { using var input = new MemoryStream(data); using var brotli = new BrotliStream(input, CompressionMode.Decompress); using var output = new MemoryStream(); brotli.CopyTo(output); return output.ToArray(); } } }