using System; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Security.Cryptography; using System.Text; using UnityEngine; public class AesEncryption : MonoBehaviour { private void Start() { string encrypted = Encrypt("cyx"); Debug.Log("Encrypted: " + encrypted); string decrypted = Decrypt(encrypted); Debug.Log("Decrypted: " + decrypted); } private static readonly string key = "1234asdf1234asdf"; // 必须是16, 24或32字符长 private static readonly string iv = "1234asdf1234asdf"; // 必须是16字符长 public static string Encrypt(string plainText) { using (Aes aesAlg = Aes.Create()) { aesAlg.Key = Encoding.UTF8.GetBytes(key); aesAlg.IV = Encoding.UTF8.GetBytes(iv); ICryptoTransform encryptor = aesAlg.CreateEncryptor(); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } byte[] encrypted = msEncrypt.ToArray(); return Convert.ToBase64String(encrypted); } } } } public static string Decrypt(string cipherText) { using (Aes aesAlg = Aes.Create()) { aesAlg.Key = Encoding.UTF8.GetBytes(key); aesAlg.IV = Encoding.UTF8.GetBytes(iv); ICryptoTransform decryptor = aesAlg.CreateDecryptor(); using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText))) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { return srDecrypt.ReadToEnd(); } } } } } }