EncryptionProcessor.cs 2.5 KB

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