ef core加密存储数据,如身份证号

一、新建项目,安装nuget

<PackageReference Include="V6.EntityFrameworkCore.DataEncryption" Version="5.0.0" />

二、本示例采用:AES+256bits(Can use a 128bits, 192bits or 256bits key)

 CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7

三、使用方法

public class Demo_DataEncryption
    {
        /// <summary>
        /// 名称
        /// </summary>
        [StringLength(50)]
        public string Name { get; set; }
 
        /// <summary>
        /// 移动电话
        /// </summary>
 
        [StringLength(50)]
        [Encrypted]
        public string TelPhone { get; set; }
 
    }
public class DatabaseContext : DbContext
{
    // Get key and IV from a Base64String or any other ways.
    // You can generate a key and IV using "AesProvider.GenerateKey()"
    private readonly byte[] _encryptionKey = Encoding.UTF8.GetBytes("..."); 
    private readonly byte[] _encryptionIV = Encoding.UTF8.GetBytes("...");
    private readonly IEncryptionProvider _provider;
 
    public DbSet<Demo_DataEncryption> DataEncryptions { get; set; }
    
    public DatabaseContext(DbContextOptions options)
        : base(options)
    {
        this._provider = new AesProvider(this._encryptionKey, this._encryptionIV);
    }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.UseEncryption(this._provider);
    }
}

 

posted @ 2024-05-02 22:57  威流  阅读(5)  评论(0编辑  收藏  举报