Implementing encryption in entity framework model classes dependency-injection entity-framework-core


A couple things off the top here, we're using .net core 2.0 and entity framework core, so we can't use the always encrypted columns in SQL server as it's not supported yet. I've discovered the Data Protection API for core, and I've been trying to figure out a way to use it to encrypt a few of the fields.

I found this article on how to add encryption to selected fields (link), but it doesn't really deal with how to do the actual encryption. So, basically, I've been trying to figure out a way to inject the Data Protection service into my model classes so I can use the Protect and Unprotect methods.

I've tried configuring our DI container (autofac) to inject it as a property, but DI doesn't seem to have anything to do with instantiating the EF objects. I also tried to set it in the OnModelCreating event of the DbContext, but that doesn't seem to work either.

Maybe someone can tell me a better way of doing this, or is my approach all wrong? Thanks.

6/23/2018 10:12:08 AM

Popular Answer

I know it's an old topic, but if you have migrated you solution to .NET Core 2.1 en EF Core 2.1, you can use this EntityFrameworkCore.DataEncryption library that I've developed. It is an EF Core plugin that adds support for encrypted fields in your database using built-in or custom encryption providers. For now, it only has the AesProvider for AES encryption, but more will be added soon.

To use it, it's really simple, tag your entities with the [Encrypted] attribute, and then override the OnModelCreating() method in your DbContext and call modelBuilder.UseEncryption([IEncryptionProvider]); and pass it an encryption provider.


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

    public string Username { get; set; }

    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)

Result when saving in database:


Then you will have encrypted fields in your database, but in your code you will be able to manipulate plain text strings.

Hope it helps.

3/28/2019 8:53:37 AM

Related Questions


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