EncryptionProcessor.cs 2.4 KB

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