AesEncryptionHelper.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace OASystem.Domain.AesEncryption
  8. {
  9. /// <summary>
  10. /// Aes加密帮助类
  11. /// </summary>
  12. public static class AesEncryptionHelper
  13. {
  14. private readonly static string Key = "FANMEIGUOJIKEY01"; // 16 字节密钥
  15. private readonly static string IV = "FANMEIGUOJIIVV01"; // 16 字节向量
  16. /// <summary>
  17. /// 加密
  18. /// </summary>
  19. /// <param name="plainText"></param>
  20. /// <returns></returns>
  21. public static string Encrypt(string plainText)
  22. {
  23. if (string.IsNullOrEmpty(plainText)) return plainText;
  24. if (EncryptionProcessor.IsEncrypted(plainText)) return plainText;
  25. using var aes = Aes.Create();
  26. aes.Key = Encoding.UTF8.GetBytes(Key);
  27. aes.IV = Encoding.UTF8.GetBytes(IV);
  28. using var encryptor = aes.CreateEncryptor();
  29. var plainBytes = Encoding.UTF8.GetBytes(plainText);
  30. var encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
  31. return Convert.ToBase64String(encryptedBytes);
  32. }
  33. /// <summary>
  34. /// 解密
  35. /// </summary>
  36. /// <param name="cipherText"></param>
  37. /// <returns></returns>
  38. public static string Decrypt(string cipherText)
  39. {
  40. if (string.IsNullOrEmpty(cipherText)) return cipherText;
  41. if (!EncryptionProcessor.IsEncrypted(cipherText)) return cipherText;
  42. using var aes = Aes.Create();
  43. aes.Key = Encoding.UTF8.GetBytes(Key);
  44. aes.IV = Encoding.UTF8.GetBytes(IV);
  45. using var decryptor = aes.CreateDecryptor();
  46. var cipherBytes = Convert.FromBase64String(cipherText);
  47. var plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
  48. return Encoding.UTF8.GetString(plainBytes);
  49. }
  50. }
  51. }