Data Encryption in Data Layer with ASP.NET Core Entity Framework

假如想象 提交于 2020-05-15 02:50:51

问题


I am currently designing a web application where the data needs to be stored encrypted.

Planned technologies used:

ASP.NET Core API ASP.NET Core Entity Framework MS SQL Server 2012 any Web Frontend Because of the specification, we need to store all data encrypted in the database.

Which would be a good approach to achieve this while still be able to use the Entity Framework & LINQ, so the developer does not have to take care of the encryption.

Is it possible to encrypt the whole database?


回答1:


A good approach would be to encrypt your data when saving changes to your database, and decrypt when reading you data from the database.

I developed a library to provide encrypted fields within an Entity Framework Core context.

You can use my EntityFrameworkCore.DataEncryption plugin to encrypt your string fields when saving changes using a built-in or custom encryption provider. Actually, only the AesProvider has been developed.

To use it, simply add the [Encrypted] attribute to your string properties of your Model and then override the OnModelCreating() method in your DbContext class, and then call the modelBuilder.UseEncryption(...) by passing it an encryption provider (AesProvider or any class that inherits from IEncryptionProvider.)

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);
    }
}

Results on saving:

encryption

Hope it helps.



来源:https://stackoverflow.com/questions/54663388/data-encryption-in-data-layer-with-asp-net-core-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!