EncryptionProcessor.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using OASystem.Domain.Attributes;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace OASystem.Domain.AesEncryption
  9. {
  10. /// <summary>
  11. /// AES 加密/解密
  12. /// </summary>
  13. public static class EncryptionProcessor
  14. {
  15. /// <summary>
  16. /// aes 加密
  17. /// </summary>
  18. /// <param name="obj"></param>
  19. public static void EncryptProperties(object obj)
  20. {
  21. if (obj == null) return;
  22. var properties = obj.GetType()
  23. .GetProperties(BindingFlags.Public | BindingFlags.Instance)
  24. .Where(p => p.IsDefined(typeof(EncryptedAttribute), false) && p.CanWrite && p.CanRead);
  25. foreach (var property in properties)
  26. {
  27. var value = property.GetValue(obj) as string;
  28. if (!string.IsNullOrEmpty(value))
  29. {
  30. var encryptedValue = AesEncryptionHelper.Encrypt(value);
  31. property.SetValue(obj, encryptedValue);
  32. }
  33. }
  34. }
  35. /// <summary>
  36. /// aes 解密
  37. /// </summary>
  38. /// <param name="obj"></param>
  39. public static void DecryptProperties(object obj)
  40. {
  41. if (obj == null) return;
  42. var properties = obj.GetType()
  43. .GetProperties(BindingFlags.Public | BindingFlags.Instance)
  44. .Where(p => p.IsDefined(typeof(EncryptedAttribute), false) && p.CanWrite && p.CanRead);
  45. foreach (var property in properties)
  46. {
  47. var value = property.GetValue(obj) as string;
  48. if (!string.IsNullOrEmpty(value))
  49. {
  50. var decryptedValue = AesEncryptionHelper.Decrypt(value);
  51. property.SetValue(obj, decryptedValue);
  52. }
  53. }
  54. }
  55. /// <summary>
  56. /// 验证字符串是否是有效的加密格式
  57. /// </summary>
  58. /// <param name="value"></param>
  59. /// <returns></returns>
  60. public static bool IsEncrypted(string value)
  61. {
  62. try
  63. {
  64. // 尝试从 Base64 解码
  65. var bytes = Convert.FromBase64String(value);
  66. // AES 加密后的数据通常会是 16 字节的倍数
  67. return bytes.Length % 16 == 0;
  68. }
  69. catch
  70. {
  71. return false; // 如果 Base64 解码失败,说明字段未加密
  72. }
  73. }
  74. }
  75. }