using System; using System.Security.Cryptography; using System.Text; namespace XGame { public class AESManager { private static readonly byte[] Key = Encoding.UTF8.GetBytes("01fsd56#@9AB183F"); // 16字节的密钥 private static readonly byte[] IV = Encoding.UTF8.GetBytes("01fsd56789A*%#3F"); // 16字节的初始向量 private static byte[] XWKey; private static byte[] XWIV; static AESManager() { Set(ChangeBytes(Encoding.UTF8.GetBytes("#@pOrhgf2026091211325890vciu%c-X"))); } public static void Set(byte[] data) { if (data.Length != 32) throw new Exception("AES Key or IV length must be 32 characters"); XWKey = new byte[16]; Array.Copy(data, 0, XWKey, 0, 16); XWIV = new byte[16]; Array.Copy(data, 16, XWIV, 0, 16); } public static byte[] ChangeBytes(byte[] src, byte xor = 0xb4) { for (int i = 0; i < src.Length; i++) { src[i] = (byte)(src[i] ^ xor); } return src; } public static string Encrypt(string plainText) { string encryptedText = Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(plainText))); return encryptedText; } public static byte[] Encrypt(byte[] plainBytes, bool bXW = true) { using (Aes aes = Aes.Create()) { if (bXW) { aes.Key = XWKey; aes.IV = XWIV; } else { aes.Key = Key; aes.IV = IV; } ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); byte[] encryptedBytes = null; using (var ms = new System.IO.MemoryStream()) { using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { cs.Write(plainBytes, 0, plainBytes.Length); cs.FlushFinalBlock(); } encryptedBytes = ms.ToArray(); } return encryptedBytes; } } public static byte[] Decrypt(byte[] encryptedBytes, bool bXW = true) { using (Aes aes = Aes.Create()) { if (bXW) { aes.Key = XWKey; aes.IV = XWIV; } else { aes.Key = Key; aes.IV = IV; } ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); byte[] decryptedBytes = null; using (var ms = new System.IO.MemoryStream(encryptedBytes)) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { byte[] decryptedData = new byte[encryptedBytes.Length]; int bytesRead = cs.Read(decryptedData, 0, decryptedData.Length); if (bytesRead == decryptedData.Length) return decryptedData; // 如果你知道解密后的数据的确切大小,你可以根据需要进行截取 byte[] trimmedData = new byte[bytesRead]; Array.Copy(decryptedData, trimmedData, bytesRead); return trimmedData; } } } } public static string Decrypt(string encryptedText) { string decryptedText = Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(encryptedText))); return decryptedText; } } // 使用示例: //string originalText = "Hello, World!"; //string encryptedText = AESExample.Encrypt(originalText); //string decryptedText = AESExample.Decrypt(encryptedText); //Console.WriteLine("Original Text: " + originalText); //Console.WriteLine("Encrypted Text: " + encryptedText); //Console.WriteLine("Decrypted Text: " + decryptedText); }