更新支持字段加密

This commit is contained in:
Falcon 2025-02-11 17:03:49 +08:00
parent a0773bbdd6
commit 0e8b885784
5 changed files with 93 additions and 1 deletions

View File

@ -23,6 +23,10 @@ namespace Falcon.SugarApi.DatabaseManager
/// 链接字符串
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// 是否支持字段加密
/// </summary>
public bool IsEnableEncrypy { get; set; } = true;
}
}

View File

@ -0,0 +1,39 @@
using System.Reflection;
namespace Falcon.SugarApi.DatabaseManager
{
/// <summary>
/// 数据库上下文字段加密支持
/// </summary>
public static class DbContextBaseEncryptExtend
{
/// <summary>
/// 设置数据库上下文支持字段加密
/// </summary>
/// <param name="dbContext">数据库上下文</param>
public static void SetEnableEncrypt(this DbContextBase dbContext) {
dbContext.Aop.DataExecuting = (value,entity) => {
var attr = entity.GetAttribute<EnableEncryptAttribute>();
var enProvider = attr.EncryptType.Assembly.CreateInstance(attr.EncryptType.FullName) as IEncrypt;
if(attr == null) {
return;
}
var newVal = enProvider.Encrypt(value.ToString());
entity.SetValue(newVal);
};
dbContext.Aop.DataExecuted = (value,entity) => {
foreach(var col in entity.EntityColumnInfos) {
var pName = col.PropertyName;
var attr = col.PropertyInfo.GetCustomAttribute<EnableEncryptAttribute>();
var enProvider = attr.EncryptType.Assembly.CreateInstance(attr.EncryptType.FullName) as IEncrypt;
if(attr == null) {
continue;
}
var newVal = enProvider.Decrypt(entity.GetValue(pName).ToString());
entity.SetValue(pName,newVal);
}
};
}
}
}

View File

@ -0,0 +1,28 @@
using System;
namespace Falcon.SugarApi.DatabaseManager
{
/// <summary>
/// 允许对字段进行加密存储
/// </summary>
[AttributeUsage(AttributeTargets.Property,AllowMultiple = false,Inherited = false)]
public class EnableEncryptAttribute:Attribute
{
/// <summary>
/// 用于加密的类型
/// </summary>
public Type EncryptType { get; set; }
/// <summary>
/// 通过提供加密解密接口实现字段加密
/// </summary>
/// <param name="encryptType">实现加密解密的类型</param>
/// <exception cref="ArgumentException">提供的类型不符合要求</exception>
public EnableEncryptAttribute(Type encryptType) {
if(!typeof(IEncrypt).IsAssignableFrom(encryptType)) {
throw new ArgumentException("encryptType must implement IEncrypt");
}
this.EncryptType = encryptType;
}
}
}

View File

@ -0,0 +1,21 @@
namespace Falcon.SugarApi.DatabaseManager
{
/// <summary>
/// 字段加密解密方法
/// </summary>
public interface IEncrypt
{
/// <summary>
/// 加密。当存储字段值进入数据库时使用该方法进行加密
/// </summary>
/// <param name="str">字段明文值</param>
/// <returns>字段密文</returns>
string Encrypt(string str);
/// <summary>
/// 解密。当读取字段内容时对数据库中的加密值进行解密
/// </summary>
/// <param name="str">字段密文</param>
/// <returns>字段明文值</returns>
string Decrypt(string str);
}
}

View File

@ -8,7 +8,7 @@
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>2.11.0</Version>
<Version>2.12.0</Version>
</PropertyGroup>
<ItemGroup>