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

.net asp.net-core c# entity-framework-core

Question

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
3
2/13/2019 6:40:58 AM

Popular Answer

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.

4
3/27/2019 5:30:03 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow