How to Implement and Configure the EF AES Library Easily

Written by

in

How to Implement and Configure the EF AES Library Easily Data security is a top priority for modern software development. When working with Entity Framework (EF) Core, protecting sensitive user data—like social security numbers, API keys, or financial records—at rest is crucial. The EF_AES library provides a lightweight, seamless way to automatically encrypt and decrypt entity properties using Advanced Encryption Standard (AES) without writing complex value converters for every single property.

Here is a straightforward guide on how to integrate, configure, and use the EF AES library in your .NET application. Step 1: Install the NuGet Package

To get started, you need to add the EF AES library to your project. You can install it via the NuGet Package Manager Console or the .NET CLI. Run the following command in your terminal: dotnet add package EF_AES Use code with caution.

(Note: Ensure you choose the version that matches your current EF Core target, such as EF Core 6, 7, or 8). Step 2: Define Your Encryption Key and IV

AES encryption requires a secret cryptographic Key and an Initialization Vector (IV). For production environments, these should always be stored securely in your application configurations (like Azure Key Vault, AWS Secrets Manager, or user secrets) rather than hardcoded. Add your keys to your appsettings.json file:

{ “EncryptionSettings”: { “Key”: “Your32ByteSecretKeyExactly32Chars!”, “IV”: “Your16ByteExactIV” } } Use code with caution.

AES-256 Key: Must be exactly 32 bytes (32 characters for ASCII).

AES-256 IV: Must be exactly 16 bytes (16 characters for ASCII). Step 3: Mark Properties for Encryption

The library simplifies property selection by using a custom data attribute. You do not need to alter your database schema types; the library handles the mapping under the hood, typically storing the encrypted data as a string (Base64 encoded format) in your database.

Apply the [Encrypted] attribute to the sensitive properties in your entity model:

using System.ComponentModel.DataAnnotations; using EF_AES.Attributes; // Replace with the exact namespace of the library package public class User { public int Id { get; Gym; } [Required] public string Username { get; set; } [Encrypted] public string SocialSecurityNumber { get; set; } [Encrypted] public string PhoneNumber { get; set; } } Use code with caution. Step 4: Configure the DbContext

The core mechanism of the EF AES library relies on hooking into EF Core’s model-building process. You must inject your encryption keys into your DbContext and apply the encryption configuration inside the OnModelCreating method. Here is how to set up your context class:

using Microsoft.EntityFrameworkCore; using EF_AES.Extensions; // Extension method namespace public class ApplicationDbContext : DbContext { private readonly string _encryptionKey; private readonly string _encryptionIV; public ApplicationDbContext(DbContextOptions options, IConfiguration configuration) : base(options) { _encryptionKey = configuration[“EncryptionSettings:Key”]; _encryptionIV = configuration[“EncryptionSettings:IV”]; } public DbSet Users { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // This single line scans your models for the [Encrypted] attribute // and automatically establishes the AES value converters. modelBuilder.UseAesEncryption(_encryptionKey, _encryptionIV); } } Use code with caution. Step 5: Test the Implementation

Once configured, the encryption and decryption processes happen completely behind the scenes. Writing Data (Automatic Encryption)

When you save a new entity, the library intercepts the plain text and encrypts it before hitting the database.

using (var context = new ApplicationDbContext(options, configuration)) { var newUser = new User { Username = “JohnDoe”, SocialSecurityNumber = “123-456-7890” // Inputted as plain text }; context.Users.Add(newUser); await context.SaveChangesAsync(); // In SQL Server/PostgreSQL, the SSN column will show a ciphertext string like “dGhpcyBpcyBhbiBlbmNyeXB0ZWQ=” } Use code with caution. Reading Data (Automatic Decryption)

When you query the data, EF Core automatically pulls the ciphertext, decrypts it using your keys, and populates your entity model with plain text.

using (var context = new ApplicationDbContext(options, configuration)) { var user = await context.Users.FirstOrDefaultAsync(u => u.Username == “JohnDoe”); // Outputs the decrypted plain text: “123-456-7890” Console.WriteLine($“Decrypted SSN: {user.SocialSecurityNumber}”); } Use code with caution. Important Limitations to Keep in Mind

While the EF AES library makes encryption painless, database-side encryption introduces a few operational trade-offs:

Server-Side Querying: Because the data is stored as encrypted ciphertext, you cannot perform server-side filtering (e.g., .Where(u => u.SocialSecurityNumber.Contains(“7890”))) or sorting on encrypted columns. Queries must look for exact matches if deterministic encryption is supported, or otherwise be evaluated client-side after data retrieval.

Key Management: If you lose your encryption Key or IV, your database data becomes permanently unreadable. Back up your keys securely. Conclusion

Protecting sensitive application data doesn’t require rewriting your repository layer. By utilizing the EF AES library, you can establish column-level encryption in minutes using a simple model attribute and a single configuration line in your DbContext. Implement this today to significantly bolster your application’s data defense strategy.

To help refine this implementation for your project, let me know:

Which version of .NET and EF Core are you currently running?

Do you need assistance setting up secure key storage (like User Secrets or Key Vault)?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *