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
{
///
/// AES 加密/解密
///
public static class EncryptionProcessor
{
///
/// aes 加密
///
///
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);
}
}
}
///
/// aes 解密
///
///
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))
{
var decryptedValue = AesEncryptionHelper.Decrypt(value);
property.SetValue(obj, decryptedValue);
}
}
}
///
/// 验证字符串是否是有效的加密格式
///
///
///
public static bool IsEncrypted(string value)
{
try
{
// 尝试从 Base64 解码
var bytes = Convert.FromBase64String(value);
// AES 加密后的数据通常会是 16 字节的倍数
return bytes.Length % 16 == 0;
}
catch
{
return false; // 如果 Base64 解码失败,说明字段未加密
}
}
}
}