好的,以下是Unity中AES加密和解密的示例代码:
加密代码:
```csharp
using System.Security.Cryptography;
using UnityEngine;
public static class AESEncryption
{
private static readonly byte[] Key = new byte[16] { 215, 254, 100, 91, 10, 69, 23, 146, 12, 175, 237, 65, 38, 205, 85, 111 };
private static readonly byte[] IV = new byte[16] { 183, 221, 44, 251, 126, 7, 77, 234, 154, 150, 97, 24, 165, 2, 153, 201 };
public static string Encrypt(string plainText)
{
byte[] encrypted;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return System.Convert.ToBase64String(encrypted);
}
}
```
解密代码:
```csharp
using System.Security.Cryptography;
using UnityEngine;
public static class AESEncryption
{
private static readonly byte[] Key = new byte[16] { 215, 254, 100, 91, 10, 69, 23, 146, 12, 175, 237, 65, 38, 205, 85, 111 };
private static readonly byte[] IV = new byte[16] { 183, 221, 44, 251, 126, 7, 77, 234, 154, 150, 97, 24, 165, 2, 153, 201 };
public static string Decrypt(string cipherText)
{
byte[] cipherBytes = System.Convert.FromBase64String(cipherText);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(cipherBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
}
```
注意:这个示例代码中的密钥和向量都是为了演示而写死的,请根据实际需求使用更安全的方式生成密钥和向量。