AesEncryption.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Net.NetworkInformation;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using UnityEngine;
  8. public class AesEncryption : MonoBehaviour
  9. {
  10. private void Start()
  11. {
  12. string encrypted = Encrypt("cyx");
  13. Debug.Log("Encrypted: " + encrypted);
  14. string decrypted = Decrypt(encrypted);
  15. Debug.Log("Decrypted: " + decrypted);
  16. }
  17. private static readonly string key = "1234asdf1234asdf"; // 必须是16, 24或32字符长
  18. private static readonly string iv = "1234asdf1234asdf"; // 必须是16字符长
  19. public static string Encrypt(string plainText)
  20. {
  21. using (Aes aesAlg = Aes.Create())
  22. {
  23. aesAlg.Key = Encoding.UTF8.GetBytes(key);
  24. aesAlg.IV = Encoding.UTF8.GetBytes(iv);
  25. ICryptoTransform encryptor = aesAlg.CreateEncryptor();
  26. using (MemoryStream msEncrypt = new MemoryStream())
  27. {
  28. using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  29. {
  30. using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
  31. {
  32. swEncrypt.Write(plainText);
  33. }
  34. byte[] encrypted = msEncrypt.ToArray();
  35. return Convert.ToBase64String(encrypted);
  36. }
  37. }
  38. }
  39. }
  40. public static string Decrypt(string cipherText)
  41. {
  42. using (Aes aesAlg = Aes.Create())
  43. {
  44. aesAlg.Key = Encoding.UTF8.GetBytes(key);
  45. aesAlg.IV = Encoding.UTF8.GetBytes(iv);
  46. ICryptoTransform decryptor = aesAlg.CreateDecryptor();
  47. using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
  48. {
  49. using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
  50. {
  51. using (StreamReader srDecrypt = new StreamReader(csDecrypt))
  52. {
  53. return srDecrypt.ReadToEnd();
  54. }
  55. }
  56. }
  57. }
  58. }
  59. }