|
@@ -0,0 +1,81 @@
|
|
|
+using OASystem.Domain.Attributes;
|
|
|
+using System;
|
|
|
+using System.Collections.Generic;
|
|
|
+using System.Linq;
|
|
|
+using System.Reflection;
|
|
|
+using System.Text;
|
|
|
+using System.Threading.Tasks;
|
|
|
+
|
|
|
+namespace OASystem.Domain.AesEncryption
|
|
|
+{
|
|
|
+ public static class EncryptionProcessor
|
|
|
+ {
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// aes 加密
|
|
|
+ /// </summary>
|
|
|
+ /// <param name="obj"></param>
|
|
|
+ public static void EncryptProperties(object obj)
|
|
|
+ {
|
|
|
+ if (obj == null) return;
|
|
|
+
|
|
|
+ var properties = obj.GetType()
|
|
|
+ .GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
|
|
+ .Where(p => p.IsDefined(typeof(EncryptedAttribute), false) && p.CanWrite && p.CanRead);
|
|
|
+
|
|
|
+ foreach (var property in properties)
|
|
|
+ {
|
|
|
+ var value = property.GetValue(obj) as string;
|
|
|
+ if (!string.IsNullOrEmpty(value))
|
|
|
+ {
|
|
|
+ var encryptedValue = AesEncryptionHelper.Encrypt(value);
|
|
|
+ property.SetValue(obj, encryptedValue);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// aes 解密
|
|
|
+ /// </summary>
|
|
|
+ /// <param name="obj"></param>
|
|
|
+ public static void DecryptProperties(object obj)
|
|
|
+ {
|
|
|
+ if (obj == null) return;
|
|
|
+
|
|
|
+ var properties = obj.GetType()
|
|
|
+ .GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
|
|
+ .Where(p => p.IsDefined(typeof(EncryptedAttribute), false) && p.CanWrite && p.CanRead);
|
|
|
+
|
|
|
+ foreach (var property in properties)
|
|
|
+ {
|
|
|
+ var value = property.GetValue(obj) as string;
|
|
|
+ if (!string.IsNullOrEmpty(value) && IsEncrypted(value))
|
|
|
+ {
|
|
|
+ var decryptedValue = AesEncryptionHelper.Decrypt(value);
|
|
|
+ property.SetValue(obj, decryptedValue);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 验证字符串是否是有效的加密格式
|
|
|
+ /// </summary>
|
|
|
+ /// <param name="value"></param>
|
|
|
+ /// <returns></returns>
|
|
|
+ public static bool IsEncrypted(string value)
|
|
|
+ {
|
|
|
+ try
|
|
|
+ {
|
|
|
+ // 尝试从 Base64 解码
|
|
|
+ var bytes = Convert.FromBase64String(value);
|
|
|
+
|
|
|
+ // AES 加密后的数据通常会是 16 字节的倍数
|
|
|
+ return bytes.Length % 16 == 0;
|
|
|
+ }
|
|
|
+ catch
|
|
|
+ {
|
|
|
+ return false; // 如果 Base64 解码失败,说明字段未加密
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|