具有Sql Server列级加密的实体框架

Noe*_*oel 9 c# sql-server ef-code-first entity-framework-6

我需要加密许多数据库列(在Sql Server 2012中).已经决定我们应该使用列级加密(在sql server中实现).在应用程序方面,我将在一些复杂的域模型之上构建一个web api.我真的想利用Entity Framework的代码第一种方法来维护一个干净的域模型.有没有人在这里有一个可行的解决方案,不涉及诉诸存储过程?理想情况下,我想以某种方式操纵实体框架生成的sql来包装某些字段来执行sql加密/解密功能.

理想情况下,例如:

modelBuilder.Entity<MyTable>().ToTable("Table1").Property(p => p.SensativeData).encrypt("keyName",authenticatorFunc);
Run Code Online (Sandbox Code Playgroud)

Eas*_*all 6

我知道它有点旧,但如果您使用 Entity Framework Core,我开发了一个 Entity Framework Core 插件,它使用string自定义属性处理字段的数据加密。实际上只有 AES 加密提供程序可用,但您可以轻松实现新的加密提供程序。在这里查看: https: //github.com/Eastral/EntityFrameworkCore.DataEncryption

它与 EF Core 2 和 3 兼容。

快速示例:

public class UserEntity
{
    public int Id { get; set; }

    [Encrypted]
    public string Username { get; set; }

    [Encrypted]
    public string Password { get; set; }

    public int Age { 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 = ...; 
    private readonly byte[] _encryptionIV = ...;
    private readonly IEncryptionProvider _provider;

    public DbSet<UserEntity> Users { 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Nit*_*nic 5

在SQL Server 2012中,列级加密主要可以通过两种方式完成,即

  1. 在实体框架中定义自定义加密功能这个博客
  2. 使用此博客并使用存储过程(其中包含表中指定字段的解密代码)在dbcontext类的实体框架(在此处执行开放对称密钥代码)中的实体框架中完成SQL单元级加密实现,以检索结果集。

在SQL Server 2016中,有一个新功能,即始终加密,并在此处在实体框架中实现。