├── src └── EntityFrameworkCore.DataEncryption │ ├── resources │ └── icon.png │ ├── Internal │ ├── PropertyAnnotations.cs │ └── EncryptionConverter.cs │ ├── Providers │ ├── AesKeySize.cs │ ├── AesKeyInfo.cs │ └── AesProvider.cs │ ├── IEncryptionProvider.cs │ ├── Attributes │ ├── StorageFormat.cs │ └── EncryptedAttribute.cs │ ├── PropertyBuilderExtensions.cs │ ├── SoftFluent.EntityFrameworkCore.DataEncryption.csproj │ └── ModelBuilderExtensions.cs ├── samples ├── AesSample.Fluent │ ├── EncryptedDatabaseContext.cs │ ├── UserEntity.cs │ ├── SoftFluent.AesSample.Fluent.csproj │ ├── DatabaseContext.cs │ └── Program.cs └── AesSample │ ├── SoftFluent.AesSample.csproj │ ├── DatabaseContext.cs │ ├── UserEntity.cs │ └── Program.cs ├── test └── EntityFrameworkCore.DataEncryption.Test │ ├── runsettings.xml │ ├── Context │ ├── DatabaseContext.cs │ ├── AuthorEntity.cs │ ├── BookEntity.cs │ └── DatabaseContextFactory.cs │ ├── SoftFluent.EntityFrameworkCore.DataEncryption.Test.csproj │ ├── ModelBuilderExtensionsTest.cs │ ├── PropertyBuilderExtensionsTest.cs │ └── Providers │ └── AesProviderTest.cs ├── LICENSE ├── .github └── workflows │ └── build.yml ├── .gitattributes ├── SoftFluent.EntityFrameworkCore.DataEncryption.sln ├── README.md └── .gitignore /src/EntityFrameworkCore.DataEncryption/resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SoftFluent/EntityFrameworkCore.DataEncryption/HEAD/src/EntityFrameworkCore.DataEncryption/resources/icon.png -------------------------------------------------------------------------------- /samples/AesSample.Fluent/EncryptedDatabaseContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace SoftFluent.AesSample.Fluent; 4 | 5 | public class EncryptedDatabaseContext : DatabaseContext 6 | { 7 | public EncryptedDatabaseContext(DbContextOptions options) 8 | : base(options, null) 9 | { 10 | } 11 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/Internal/PropertyAnnotations.cs: -------------------------------------------------------------------------------- 1 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Internal; 2 | 3 | internal class PropertyAnnotations 4 | { 5 | public const string IsEncrypted = "SoftFluent.EntityFrameworkCore.DataEncryption.IsEncrypted"; 6 | public const string StorageFormat = "SoftFluent.EntityFrameworkCore.DataEncryption.StorageFormat"; 7 | } 8 | -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/runsettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | opencover 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /samples/AesSample.Fluent/UserEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SoftFluent.AesSample.Fluent; 4 | 5 | public class UserEntity 6 | { 7 | public Guid Id { get; set; } 8 | 9 | public string FirstName { get; set; } 10 | 11 | public string LastName { get; set; } 12 | 13 | public string Email { get; set; } 14 | 15 | public string Notes { get; set; } 16 | 17 | public byte[] EncryptedData { get; set; } 18 | 19 | public byte[] EncryptedDataAsString { get; set; } 20 | } 21 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/Providers/AesKeySize.cs: -------------------------------------------------------------------------------- 1 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Providers; 2 | 3 | /// 4 | /// Specifies the available AES Key sizes used for generating encryption keys and initialization vectors. 5 | /// 6 | /// 7 | /// The key sizes are defined in bits. 8 | /// 9 | public enum AesKeySize : uint 10 | { 11 | /// 12 | /// AES 128 bits key size. 13 | /// 14 | AES128Bits = 128, 15 | 16 | /// 17 | /// AES 192 bits key size. 18 | /// 19 | AES192Bits = 192, 20 | 21 | /// 22 | /// AES 256 bits key size. 23 | /// 24 | AES256Bits = 256 25 | } 26 | -------------------------------------------------------------------------------- /samples/AesSample/SoftFluent.AesSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net10.0 6 | 10 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/IEncryptionProvider.cs: -------------------------------------------------------------------------------- 1 | namespace SoftFluent.EntityFrameworkCore.DataEncryption; 2 | 3 | /// 4 | /// Provides a mechanism to encrypt and decrypt data. 5 | /// 6 | public interface IEncryptionProvider 7 | { 8 | /// 9 | /// Encrypts the given input byte array. 10 | /// 11 | /// Input to encrypt. 12 | /// Encrypted input. 13 | byte[] Encrypt(byte[] input); 14 | 15 | /// 16 | /// Decrypts the given input byte array. 17 | /// 18 | /// Input to decrypt. 19 | /// Decrypted input. 20 | byte[] Decrypt(byte[] input); 21 | } 22 | -------------------------------------------------------------------------------- /samples/AesSample.Fluent/SoftFluent.AesSample.Fluent.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net10.0 6 | 10 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /samples/AesSample/DatabaseContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using SoftFluent.EntityFrameworkCore.DataEncryption; 3 | 4 | namespace SoftFluent.AesSample; 5 | 6 | public class DatabaseContext : DbContext 7 | { 8 | private readonly IEncryptionProvider _encryptionProvider; 9 | 10 | public DbSet Users { get; set; } 11 | 12 | public DatabaseContext(DbContextOptions options, IEncryptionProvider encryptionProvider) 13 | : base(options) 14 | { 15 | _encryptionProvider = encryptionProvider; 16 | } 17 | 18 | protected override void OnModelCreating(ModelBuilder modelBuilder) 19 | { 20 | modelBuilder.UseEncryption(_encryptionProvider); 21 | 22 | base.OnModelCreating(modelBuilder); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/Attributes/StorageFormat.cs: -------------------------------------------------------------------------------- 1 | namespace SoftFluent.ComponentModel.DataAnnotations; 2 | 3 | /// 4 | /// Represents the storage format for an encrypted value. 5 | /// 6 | public enum StorageFormat 7 | { 8 | /// 9 | /// The format is determined by the model data type. 10 | /// 11 | Default, 12 | 13 | /// 14 | /// The value is stored in binary. 15 | /// 16 | Binary, 17 | 18 | /// 19 | /// The value is stored in a Base64-encoded string. 20 | /// 21 | /// 22 | /// NB: If the source property is a , 23 | /// and no encryption provider is configured, 24 | /// the string will not be modified. 25 | /// 26 | Base64, 27 | } -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/Context/DatabaseContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Test.Context; 4 | 5 | public class DatabaseContext : DbContext 6 | { 7 | private readonly IEncryptionProvider _encryptionProvider; 8 | 9 | public DbSet Authors { get; set; } 10 | 11 | public DbSet Books { get; set; } 12 | 13 | public DatabaseContext(DbContextOptions options) 14 | : base(options) 15 | { } 16 | 17 | public DatabaseContext(DbContextOptions options, IEncryptionProvider encryptionProvider = null) 18 | : base(options) 19 | { 20 | _encryptionProvider = encryptionProvider; 21 | } 22 | protected override void OnModelCreating(ModelBuilder modelBuilder) 23 | { 24 | modelBuilder.UseEncryption(_encryptionProvider); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /samples/AesSample/UserEntity.cs: -------------------------------------------------------------------------------- 1 | using SoftFluent.ComponentModel.DataAnnotations; 2 | using System; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | 6 | namespace SoftFluent.AesSample; 7 | 8 | public class UserEntity 9 | { 10 | [Key] 11 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 12 | public Guid Id { get; set; } 13 | 14 | [Required] 15 | public string FirstName { get; set; } 16 | 17 | [Required] 18 | public string LastName { get; set; } 19 | 20 | [Required] 21 | [Encrypted] 22 | public string Email { get; set; } 23 | 24 | [Required] 25 | [Encrypted(StorageFormat.Binary)] 26 | public string Notes { get; set; } 27 | 28 | [Required] 29 | [Encrypted] 30 | public byte[] EncryptedData { get; set; } 31 | 32 | [Required] 33 | [Encrypted(StorageFormat.Base64)] 34 | [Column(TypeName = "TEXT")] 35 | public byte[] EncryptedDataAsString { get; set; } 36 | } 37 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/PropertyBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 2 | using SoftFluent.EntityFrameworkCore.DataEncryption.Internal; 3 | using System; 4 | using SoftFluent.ComponentModel.DataAnnotations; 5 | 6 | namespace SoftFluent.EntityFrameworkCore.DataEncryption; 7 | 8 | /// 9 | /// Provides extensions for the type. 10 | /// 11 | public static class PropertyBuilderExtensions 12 | { 13 | public static PropertyBuilder IsEncrypted(this PropertyBuilder builder, StorageFormat storageFormat = StorageFormat.Default) 14 | { 15 | if (builder is null) 16 | { 17 | throw new ArgumentNullException(nameof(builder)); 18 | } 19 | 20 | builder.HasAnnotation(PropertyAnnotations.IsEncrypted, true); 21 | builder.HasAnnotation(PropertyAnnotations.StorageFormat, storageFormat); 22 | 23 | return builder; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/Attributes/EncryptedAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SoftFluent.ComponentModel.DataAnnotations; 4 | 5 | /// 6 | /// Specifies that the data field value should be encrypted. 7 | /// 8 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 9 | public sealed class EncryptedAttribute : Attribute 10 | { 11 | /// 12 | /// Returns the storage format for the database value. 13 | /// 14 | public StorageFormat Format { get; } 15 | 16 | /// 17 | /// Initializes a new instance of the class. 18 | /// 19 | /// 20 | /// The storage format. 21 | /// 22 | public EncryptedAttribute(StorageFormat format) 23 | { 24 | Format = format; 25 | } 26 | 27 | /// 28 | /// Initializes a new instance of the class. 29 | /// 30 | public EncryptedAttribute() 31 | : this(StorageFormat.Default) 32 | { 33 | } 34 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 SoftFluent 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/Context/AuthorEntity.cs: -------------------------------------------------------------------------------- 1 | using SoftFluent.ComponentModel.DataAnnotations; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.ComponentModel.DataAnnotations; 5 | using System.ComponentModel.DataAnnotations.Schema; 6 | 7 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Test.Context; 8 | 9 | public sealed class AuthorEntity 10 | { 11 | [Key] 12 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 13 | public int Id { get; set; } 14 | 15 | public Guid UniqueId { get; set; } 16 | 17 | [Required] 18 | [Encrypted] 19 | public string FirstName { get; set; } 20 | 21 | [Required] 22 | [Encrypted(StorageFormat.Binary)] 23 | [Column(TypeName = "BLOB")] 24 | public string LastName { get; set; } 25 | 26 | [Required] 27 | public int Age { get; set; } 28 | 29 | public IList Books { get; set; } 30 | 31 | public AuthorEntity(string firstName, string lastName, int age) 32 | { 33 | FirstName = firstName; 34 | LastName = lastName; 35 | Age = age; 36 | Books = new List(); 37 | UniqueId = Guid.NewGuid(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: .NET 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build-library: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout repository 15 | uses: actions/checkout@v3 16 | 17 | - name: Setup .NET Core 18 | uses: actions/setup-dotnet@v3 19 | with: 20 | dotnet-version: | 21 | 3.1.x 22 | 5.0.x 23 | 6.0.x 24 | 7.0.x 25 | 8.0.x 26 | 9.0.x 27 | 10.0.x 28 | 29 | - name: Display .NET version 30 | run: dotnet --version 31 | 32 | - name: Restore dependencies 33 | run: dotnet restore 34 | 35 | - name: Build 36 | run: dotnet build SoftFluent.EntityFrameworkCore.DataEncryption.sln --configuration Release -f net10.0 --no-restore 37 | 38 | - name: Run unit tests 39 | run: dotnet test --configuration Release --collect:"XPlat Code Coverage" --settings ./test/EntityFrameworkCore.DataEncryption.Test/runsettings.xml 40 | 41 | - name: Copy coverage results 42 | run: cp ./test/EntityFrameworkCore.DataEncryption.Test/TestResults/**/*.xml ./test/EntityFrameworkCore.DataEncryption.Test/TestResults/ 43 | 44 | -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/Context/BookEntity.cs: -------------------------------------------------------------------------------- 1 | using SoftFluent.ComponentModel.DataAnnotations; 2 | using System; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | 6 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Test.Context; 7 | 8 | public sealed class BookEntity 9 | { 10 | [Key] 11 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 12 | public int Id { get; set; } 13 | 14 | public Guid UniqueId { get; set; } 15 | 16 | [Required] 17 | [Encrypted] 18 | public string Name { get; set; } 19 | 20 | [Required] 21 | public int NumberOfPages { get; set; } 22 | 23 | [Required] 24 | public int AuthorId { get; set; } 25 | 26 | [ForeignKey(nameof(AuthorId))] 27 | public AuthorEntity Author { get; set; } 28 | 29 | [Encrypted(StorageFormat.Base64)] 30 | [Column(TypeName = "TEXT")] 31 | public byte[] Content { get; set; } 32 | 33 | [Encrypted] 34 | [Column(TypeName = "BLOB")] 35 | public byte[] Summary { get; set; } 36 | 37 | public BookEntity(string name, int numberOfPages, byte[] content, byte[] summary) 38 | { 39 | Name = name; 40 | NumberOfPages = numberOfPages; 41 | UniqueId = Guid.NewGuid(); 42 | Content = content; 43 | Summary = summary; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/SoftFluent.EntityFrameworkCore.DataEncryption.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net10.0 5 | 10 6 | false 7 | SoftFluent.EntityFrameworkCore.Encryption.Test 8 | SoftFluent.EntityFrameworkCore.Encryption.Test 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | 23 | 24 | 25 | 26 | all 27 | runtime; build; native; contentfiles; analyzers 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /samples/AesSample.Fluent/DatabaseContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using SoftFluent.EntityFrameworkCore.DataEncryption; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | using SoftFluent.ComponentModel.DataAnnotations; 5 | 6 | namespace SoftFluent.AesSample.Fluent; 7 | 8 | public class DatabaseContext : DbContext 9 | { 10 | private readonly IEncryptionProvider _encryptionProvider; 11 | 12 | public DbSet Users { get; set; } 13 | 14 | public DatabaseContext(DbContextOptions options, IEncryptionProvider encryptionProvider) 15 | : base(options) 16 | { 17 | _encryptionProvider = encryptionProvider; 18 | } 19 | 20 | protected override void OnModelCreating(ModelBuilder modelBuilder) 21 | { 22 | EntityTypeBuilder userEntityBuilder = modelBuilder.Entity(); 23 | 24 | userEntityBuilder.HasKey(x => x.Id); 25 | userEntityBuilder.Property(x => x.Id).IsRequired().ValueGeneratedOnAdd(); 26 | userEntityBuilder.Property(x => x.FirstName).IsRequired(); 27 | userEntityBuilder.Property(x => x.LastName).IsRequired(); 28 | userEntityBuilder.Property(x => x.Email).IsRequired().IsEncrypted(); 29 | userEntityBuilder.Property(x => x.Notes).IsRequired().HasColumnType("BLOB").IsEncrypted(StorageFormat.Binary); 30 | userEntityBuilder.Property(x => x.EncryptedData).IsRequired().IsEncrypted(); 31 | userEntityBuilder.Property(x => x.EncryptedDataAsString).IsRequired().HasColumnType("TEXT").IsEncrypted(StorageFormat.Base64); 32 | 33 | if (_encryptionProvider is not null) 34 | { 35 | modelBuilder.UseEncryption(_encryptionProvider); 36 | } 37 | 38 | base.OnModelCreating(modelBuilder); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /samples/AesSample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Data.Sqlite; 2 | using Microsoft.EntityFrameworkCore; 3 | using SoftFluent.EntityFrameworkCore.DataEncryption.Providers; 4 | using System; 5 | using System.Linq; 6 | 7 | namespace SoftFluent.AesSample; 8 | 9 | static class Program 10 | { 11 | static void Main() 12 | { 13 | using SqliteConnection connection = new("DataSource=:memory:"); 14 | connection.Open(); 15 | 16 | var options = new DbContextOptionsBuilder() 17 | .UseSqlite(connection) 18 | .Options; 19 | 20 | // AES key randomly generated at each run. 21 | AesKeyInfo keyInfo = AesProvider.GenerateKey(AesKeySize.AES256Bits); 22 | byte[] encryptionKey = keyInfo.Key; 23 | byte[] encryptionIV = keyInfo.IV; 24 | var encryptionProvider = new AesProvider(encryptionKey, encryptionIV); 25 | 26 | using (var context = new DatabaseContext(options, encryptionProvider)) 27 | { 28 | context.Database.EnsureCreated(); 29 | 30 | var user = new UserEntity 31 | { 32 | FirstName = "John", 33 | LastName = "Doe", 34 | Email = "john@doe.com", 35 | Notes = "Hello world!", 36 | EncryptedData = new byte[2] { 1, 2 }, 37 | EncryptedDataAsString = new byte[2] { 3, 4 } 38 | }; 39 | 40 | context.Users.Add(user); 41 | context.SaveChanges(); 42 | 43 | Console.WriteLine($"Users count: {context.Users.Count()}"); 44 | } 45 | 46 | using (var context = new DatabaseContext(options, encryptionProvider)) 47 | { 48 | UserEntity user = context.Users.First(); 49 | 50 | Console.WriteLine($"User: {user.FirstName} {user.LastName} - {user.Email} (Notes: {user.Notes})"); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /samples/AesSample.Fluent/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Data.Sqlite; 2 | using SoftFluent.EntityFrameworkCore.DataEncryption.Providers; 3 | using Microsoft.EntityFrameworkCore; 4 | using System; 5 | using System.Linq; 6 | 7 | namespace SoftFluent.AesSample.Fluent; 8 | 9 | internal class Program 10 | { 11 | static void Main(string[] args) 12 | { 13 | using SqliteConnection connection = new("DataSource=:memory:"); 14 | connection.Open(); 15 | 16 | var options = new DbContextOptionsBuilder() 17 | .UseSqlite(connection) 18 | .Options; 19 | 20 | // AES key randomly generated at each run. 21 | AesKeyInfo keyInfo = AesProvider.GenerateKey(AesKeySize.AES256Bits); 22 | byte[] encryptionKey = keyInfo.Key; 23 | byte[] encryptionIV = keyInfo.IV; 24 | var encryptionProvider = new AesProvider(encryptionKey, encryptionIV); 25 | 26 | using (var context = new DatabaseContext(options, encryptionProvider)) 27 | { 28 | context.Database.EnsureCreated(); 29 | 30 | var user = new UserEntity 31 | { 32 | FirstName = "John", 33 | LastName = "Doe", 34 | Email = "john@doe.com", 35 | Notes = "Hello world!", 36 | EncryptedData = new byte[2] { 1, 2 }, 37 | EncryptedDataAsString = new byte[2] { 3, 4 } 38 | }; 39 | 40 | context.Users.Add(user); 41 | context.SaveChanges(); 42 | 43 | Console.WriteLine($"Users count: {context.Users.Count()}"); 44 | } 45 | 46 | using (var context = new EncryptedDatabaseContext(options)) 47 | { 48 | UserEntity user = context.Users.First(); 49 | 50 | Console.WriteLine($"Encrypted User: {user.FirstName} {user.LastName} - {user.Email} (Notes: {user.Notes})"); 51 | } 52 | 53 | using (var context = new DatabaseContext(options, encryptionProvider)) 54 | { 55 | UserEntity user = context.Users.First(); 56 | 57 | Console.WriteLine($"User: {user.FirstName} {user.LastName} - {user.Email} (Notes: {user.Notes})"); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/Context/DatabaseContextFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Data.Sqlite; 2 | using Microsoft.EntityFrameworkCore; 3 | using System; 4 | using System.Data.Common; 5 | 6 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Test.Context; 7 | 8 | /// 9 | /// Database context factory used to create entity framework new . 10 | /// 11 | public sealed class DatabaseContextFactory : IDisposable 12 | { 13 | private const string InMemoryDatabaseConnectionString = "DataSource=:memory:"; 14 | private const string DatabaseConnectionString = "DataSource={0}"; 15 | private readonly DbConnection _connection; 16 | 17 | /// 18 | /// Creates a new instance. 19 | /// 20 | public DatabaseContextFactory(string databaseName = null) 21 | { 22 | _connection = new SqliteConnection(string.IsNullOrEmpty(databaseName) ? InMemoryDatabaseConnectionString : DatabaseConnectionString.Replace("{0}", databaseName)); 23 | _connection.Open(); 24 | } 25 | 26 | /// 27 | /// Creates a new in memory database context. 28 | /// 29 | /// Context 30 | /// Encryption provider 31 | /// 32 | public TContext CreateContext(IEncryptionProvider provider = null) where TContext : DbContext 33 | { 34 | var context = Activator.CreateInstance(typeof(TContext), CreateOptions(), provider) as TContext; 35 | 36 | context.Database.EnsureCreated(); 37 | 38 | return context; 39 | } 40 | 41 | /// 42 | /// Creates a new instance using SQLite. 43 | /// 44 | /// 45 | /// 46 | public DbContextOptions CreateOptions() where TContext : DbContext 47 | => new DbContextOptionsBuilder().UseSqlite(_connection).Options; 48 | 49 | /// 50 | /// Dispose the SQLite in memory connection. 51 | /// 52 | public void Dispose() 53 | { 54 | _connection?.Dispose(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/Providers/AesKeyInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Providers; 4 | 5 | /// 6 | /// Defines an AES key info structure containing a Key and Initialization Vector used for the AES encryption algorithm. 7 | /// 8 | public readonly struct AesKeyInfo : IEquatable 9 | { 10 | /// 11 | /// Gets the AES key. 12 | /// 13 | public byte[] Key { get; } 14 | 15 | /// 16 | /// Gets the AES initialization vector. 17 | /// 18 | public byte[] IV { get; } 19 | 20 | /// 21 | /// Creates a new . 22 | /// 23 | /// AES key. 24 | /// AES initialization vector. 25 | internal AesKeyInfo(byte[] key, byte[] iv) 26 | { 27 | Key = key; 28 | IV = iv; 29 | } 30 | 31 | /// 32 | /// Determines whether the current is equal to another . 33 | /// 34 | /// 35 | /// 36 | public bool Equals(AesKeyInfo other) => (Key, IV) == (other.Key, other.IV); 37 | 38 | /// 39 | /// Determines whether the current object is equal to another object of the same type. 40 | /// 41 | /// 42 | /// 43 | public override bool Equals(object obj) => (obj is AesKeyInfo keyInfo) && Equals(keyInfo); 44 | 45 | /// 46 | /// Calculates the hash code for the current instance. 47 | /// 48 | /// 49 | public override int GetHashCode() => (Key, IV).GetHashCode(); 50 | 51 | /// 52 | /// Determines whether the current is equal to another . 53 | /// 54 | /// 55 | /// 56 | /// 57 | public static bool operator ==(AesKeyInfo left, AesKeyInfo right) => Equals(left, right); 58 | 59 | /// 60 | /// Determines whether the current is not equal to another . 61 | /// 62 | /// 63 | /// 64 | /// 65 | public static bool operator !=(AesKeyInfo left, AesKeyInfo right) => !Equals(left, right); 66 | } 67 | -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/ModelBuilderExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using SoftFluent.EntityFrameworkCore.DataEncryption.Test.Context; 3 | using SoftFluent.EntityFrameworkCore.DataEncryption; 4 | using SoftFluent.EntityFrameworkCore.DataEncryption.Providers; 5 | using System; 6 | using System.ComponentModel.DataAnnotations; 7 | using System.ComponentModel.DataAnnotations.Schema; 8 | using Xunit; 9 | using SoftFluent.ComponentModel.DataAnnotations; 10 | 11 | namespace SoftFluent.EntityFrameworkCore.Encryption.Test; 12 | 13 | public class ModelBuilderExtensionsTest 14 | { 15 | [Fact] 16 | public void ModelBuilderShouldNeverBeNullTest() 17 | { 18 | Assert.Throws(() => ModelBuilderExtensions.UseEncryption(null, null)); 19 | } 20 | 21 | [Fact] 22 | public void EncryptionProviderShouldNeverBeNullTest() 23 | { 24 | using var contextFactory = new DatabaseContextFactory(); 25 | 26 | Assert.Throws(() => contextFactory.CreateContext(null)); 27 | } 28 | 29 | [Fact] 30 | public void UseEncryptionWithUnsupportedTypeTest() 31 | { 32 | AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(AesKeySize.AES256Bits); 33 | var provider = new AesProvider(encryptionKeyInfo.Key, encryptionKeyInfo.IV); 34 | 35 | using var contextFactory = new DatabaseContextFactory(); 36 | 37 | Assert.Throws(() => contextFactory.CreateContext(provider)); 38 | } 39 | 40 | private class InvalidPropertyEntity 41 | { 42 | [Key] 43 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 44 | public int Id { get; set; } 45 | 46 | [Encrypted] 47 | public string Name { get; set; } 48 | 49 | [Encrypted] 50 | public int Age { get; set; } 51 | } 52 | 53 | private class InvalidPropertyDbContext : DbContext 54 | { 55 | private readonly IEncryptionProvider _encryptionProvider; 56 | 57 | public DbSet InvalidEntities { get; set; } 58 | 59 | public InvalidPropertyDbContext(DbContextOptions options) 60 | : base(options) 61 | { } 62 | 63 | public InvalidPropertyDbContext(DbContextOptions options, IEncryptionProvider encryptionProvider = null) 64 | : base(options) 65 | { 66 | _encryptionProvider = encryptionProvider; 67 | } 68 | protected override void OnModelCreating(ModelBuilder modelBuilder) 69 | { 70 | modelBuilder.UseEncryption(_encryptionProvider); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/Internal/EncryptionConverter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 2 | using System; 3 | using SoftFluent.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Internal; 7 | 8 | /// 9 | /// Defines the internal encryption converter for string values. 10 | /// 11 | /// 12 | /// 13 | internal sealed class EncryptionConverter : ValueConverter 14 | { 15 | /// 16 | /// Creates a new instance. 17 | /// 18 | /// Encryption provider to use. 19 | /// Encryption storage format. 20 | /// Mapping hints. 21 | public EncryptionConverter(IEncryptionProvider encryptionProvider, StorageFormat storageFormat, ConverterMappingHints mappingHints = null) 22 | : base( 23 | x => Encrypt(x, encryptionProvider, storageFormat), 24 | x => Decrypt(x, encryptionProvider, storageFormat), 25 | mappingHints) 26 | { 27 | } 28 | 29 | private static TOutput Encrypt(TInput input, IEncryptionProvider encryptionProvider, StorageFormat storageFormat) 30 | { 31 | byte[] inputData = input switch 32 | { 33 | string => !string.IsNullOrEmpty(input.ToString()) ? Encoding.UTF8.GetBytes(input.ToString()) : null, 34 | byte[] => input as byte[], 35 | _ => null, 36 | }; 37 | 38 | byte[] encryptedRawBytes = encryptionProvider.Encrypt(inputData); 39 | 40 | if (encryptedRawBytes is null) 41 | { 42 | return default; 43 | } 44 | 45 | object encryptedData = storageFormat switch 46 | { 47 | StorageFormat.Default or StorageFormat.Base64 => Convert.ToBase64String(encryptedRawBytes), 48 | _ => encryptedRawBytes 49 | }; 50 | 51 | return (TOutput)Convert.ChangeType(encryptedData, typeof(TOutput)); 52 | } 53 | 54 | private static TModel Decrypt(TProvider input, IEncryptionProvider encryptionProvider, StorageFormat storageFormat) 55 | { 56 | Type destinationType = typeof(TModel); 57 | byte[] inputData = storageFormat switch 58 | { 59 | StorageFormat.Default or StorageFormat.Base64 => Convert.FromBase64String(input.ToString()), 60 | _ => input as byte[] 61 | }; 62 | byte[] decryptedRawBytes = encryptionProvider.Decrypt(inputData); 63 | object decryptedData = null; 64 | 65 | if (decryptedRawBytes != null && destinationType == typeof(string)) 66 | { 67 | decryptedData = Encoding.UTF8.GetString(decryptedRawBytes).Trim('\0'); 68 | } 69 | else if (destinationType == typeof(byte[])) 70 | { 71 | decryptedData = decryptedRawBytes; 72 | } 73 | 74 | return (TModel)Convert.ChangeType(decryptedData, typeof(TModel)); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/SoftFluent.EntityFrameworkCore.DataEncryption.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;net6.0;net7.0;net8.0;net9.0;net10.0 5 | 10.0 6 | true 7 | SoftFluent.EntityFrameworkCore.DataEncryption 8 | SoftFluent.EntityFrameworkCore.DataEncryption 9 | true 10 | 8.0.0 11 | SoftFluent 12 | SoftFluent 13 | EntityFrameworkCore.DataEncryption 14 | https://github.com/SoftFluent/EntityFrameworkCore.DataEncryption 15 | https://github.com/SoftFluent/EntityFrameworkCore.DataEncryption.git 16 | git 17 | true 18 | true 19 | entity-framework-core, extensions, dotnet-core, dotnet, encryption, fluent-api 20 | icon.png 21 | SoftFluent © 2019 - 2025 22 | A plugin for Microsoft.EntityFrameworkCore to add support of encrypted fields using built-in or custom encryption providers. 23 | LICENSE 24 | https://github.com/SoftFluent/EntityFrameworkCore.DataEncryption/releases/tag/v8.0.0 25 | README.md 26 | 27 | 28 | 29 | Auto 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | True 57 | 58 | 59 | 60 | True 61 | \ 62 | 63 | 64 | 65 | 66 | 67 | 68 | <_Parameter1>SoftFluent.EntityFrameworkCore.Encryption.Test 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /SoftFluent.EntityFrameworkCore.DataEncryption.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.3.32901.215 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{3EC10767-1816-46B2-A78E-9856071CCFDB}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{E4089551-AF4E-41B3-A6F8-2501A3BE0E0C}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SoftFluent.EntityFrameworkCore.DataEncryption", "src\EntityFrameworkCore.DataEncryption\SoftFluent.EntityFrameworkCore.DataEncryption.csproj", "{D037F8D0-E606-4C5A-8669-DB6AAE7B056B}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SoftFluent.EntityFrameworkCore.DataEncryption.Test", "test\EntityFrameworkCore.DataEncryption.Test\SoftFluent.EntityFrameworkCore.DataEncryption.Test.csproj", "{5E023B6A-0B47-4EC2-90B9-2DF998E58ADB}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "global", "global", "{3A8D800E-77BD-44EF-82DB-C672281ECAAA}" 15 | ProjectSection(SolutionItems) = preProject 16 | .gitattributes = .gitattributes 17 | .gitignore = .gitignore 18 | README.md = README.md 19 | EndProjectSection 20 | EndProject 21 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{64C3D7D1-67B8-4070-AE67-C71B761535CC}" 22 | EndProject 23 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SoftFluent.AesSample", "samples\AesSample\SoftFluent.AesSample.csproj", "{8AA1E576-4016-4623-96C8-90330F05F9A8}" 24 | EndProject 25 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{EEF46CDC-C438-48FC-BEF7-83AEE26C63F7}" 26 | EndProject 27 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{4F549FEF-C57B-4A34-A2C7-8A632762DF85}" 28 | ProjectSection(SolutionItems) = preProject 29 | .github\workflows\build.yml = .github\workflows\build.yml 30 | EndProjectSection 31 | EndProject 32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SoftFluent.AesSample.Fluent", "samples\AesSample.Fluent\SoftFluent.AesSample.Fluent.csproj", "{CF04DE64-713F-4ED3-9C14-B7C11D22454C}" 33 | EndProject 34 | Global 35 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 36 | Debug|Any CPU = Debug|Any CPU 37 | Release|Any CPU = Release|Any CPU 38 | EndGlobalSection 39 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 40 | {D037F8D0-E606-4C5A-8669-DB6AAE7B056B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {D037F8D0-E606-4C5A-8669-DB6AAE7B056B}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {D037F8D0-E606-4C5A-8669-DB6AAE7B056B}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {D037F8D0-E606-4C5A-8669-DB6AAE7B056B}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {5E023B6A-0B47-4EC2-90B9-2DF998E58ADB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {5E023B6A-0B47-4EC2-90B9-2DF998E58ADB}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {5E023B6A-0B47-4EC2-90B9-2DF998E58ADB}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {5E023B6A-0B47-4EC2-90B9-2DF998E58ADB}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {8AA1E576-4016-4623-96C8-90330F05F9A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {8AA1E576-4016-4623-96C8-90330F05F9A8}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {8AA1E576-4016-4623-96C8-90330F05F9A8}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {8AA1E576-4016-4623-96C8-90330F05F9A8}.Release|Any CPU.Build.0 = Release|Any CPU 52 | {CF04DE64-713F-4ED3-9C14-B7C11D22454C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 53 | {CF04DE64-713F-4ED3-9C14-B7C11D22454C}.Debug|Any CPU.Build.0 = Debug|Any CPU 54 | {CF04DE64-713F-4ED3-9C14-B7C11D22454C}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {CF04DE64-713F-4ED3-9C14-B7C11D22454C}.Release|Any CPU.Build.0 = Release|Any CPU 56 | EndGlobalSection 57 | GlobalSection(SolutionProperties) = preSolution 58 | HideSolutionNode = FALSE 59 | EndGlobalSection 60 | GlobalSection(NestedProjects) = preSolution 61 | {D037F8D0-E606-4C5A-8669-DB6AAE7B056B} = {3EC10767-1816-46B2-A78E-9856071CCFDB} 62 | {5E023B6A-0B47-4EC2-90B9-2DF998E58ADB} = {E4089551-AF4E-41B3-A6F8-2501A3BE0E0C} 63 | {8AA1E576-4016-4623-96C8-90330F05F9A8} = {64C3D7D1-67B8-4070-AE67-C71B761535CC} 64 | {EEF46CDC-C438-48FC-BEF7-83AEE26C63F7} = {3A8D800E-77BD-44EF-82DB-C672281ECAAA} 65 | {4F549FEF-C57B-4A34-A2C7-8A632762DF85} = {EEF46CDC-C438-48FC-BEF7-83AEE26C63F7} 66 | {CF04DE64-713F-4ED3-9C14-B7C11D22454C} = {64C3D7D1-67B8-4070-AE67-C71B761535CC} 67 | EndGlobalSection 68 | GlobalSection(ExtensibilityGlobals) = postSolution 69 | SolutionGuid = {4997BAE9-29BF-4D79-AE5E-5605E7A0F049} 70 | EndGlobalSection 71 | EndGlobal 72 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/Providers/AesProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Security.Cryptography; 4 | 5 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Providers; 6 | 7 | /// 8 | /// Implements the Advanced Encryption Standard (AES) symmetric algorithm. 9 | /// 10 | public class AesProvider : IEncryptionProvider 11 | { 12 | /// 13 | /// AES block size constant. 14 | /// 15 | public const int AesBlockSize = 128; 16 | 17 | /// 18 | /// Initialization vector size constant. 19 | /// 20 | public const int InitializationVectorSize = 16; 21 | 22 | private readonly byte[] _key; 23 | private readonly byte[] _iv; 24 | private readonly CipherMode _mode; 25 | private readonly PaddingMode _padding; 26 | 27 | /// 28 | /// Creates a new instance used to perform symmetric encryption and decryption on strings. 29 | /// 30 | /// AES key used for the symmetric encryption. 31 | /// AES Initialization Vector used for the symmetric encryption. 32 | /// Mode for operation used in the symmetric encryption. 33 | /// Padding mode used in the symmetric encryption. 34 | public AesProvider(byte[] key, byte[] initializationVector, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) 35 | { 36 | _key = key ?? throw new ArgumentNullException(nameof(key), ""); 37 | _iv = initializationVector ?? throw new ArgumentNullException(nameof(initializationVector), ""); 38 | _mode = mode; 39 | _padding = padding; 40 | } 41 | 42 | /// 43 | public byte[] Encrypt(byte[] input) 44 | { 45 | if (input is null || input.Length == 0) 46 | { 47 | return null; 48 | } 49 | 50 | using Aes aes = CreateCryptographyProvider(_key, _iv, _mode, _padding); 51 | using ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV); 52 | using MemoryStream memoryStream = new(); 53 | using CryptoStream cryptoStream = new(memoryStream, transform, CryptoStreamMode.Write); 54 | 55 | cryptoStream.Write(input, 0, input.Length); 56 | cryptoStream.FlushFinalBlock(); 57 | memoryStream.Seek(0L, SeekOrigin.Begin); 58 | 59 | return StreamToBytes(memoryStream); 60 | } 61 | 62 | /// 63 | public byte[] Decrypt(byte[] input) 64 | { 65 | if (input is null || input.Length == 0) 66 | { 67 | return null; 68 | } 69 | 70 | using Aes aes = CreateCryptographyProvider(_key, _iv, _mode, _padding); 71 | using ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV); 72 | using MemoryStream memoryStream = new(input); 73 | using CryptoStream cryptoStream = new(memoryStream, transform, CryptoStreamMode.Read); 74 | 75 | return StreamToBytes(cryptoStream); 76 | } 77 | 78 | /// 79 | /// Converts a into a byte array. 80 | /// 81 | /// Stream. 82 | /// The stream's content as a byte array. 83 | internal static byte[] StreamToBytes(Stream stream) 84 | { 85 | if (stream is MemoryStream ms) 86 | { 87 | return ms.ToArray(); 88 | } 89 | 90 | using var output = new MemoryStream(); 91 | stream.CopyTo(output); 92 | return output.ToArray(); 93 | } 94 | 95 | /// 96 | /// Generates an AES cryptography provider. 97 | /// 98 | /// 99 | private static Aes CreateCryptographyProvider(byte[] key, byte[] iv, CipherMode mode, PaddingMode padding) 100 | { 101 | var aes = Aes.Create(); 102 | 103 | aes.Mode = mode; 104 | aes.KeySize = key.Length * 8; 105 | aes.BlockSize = AesBlockSize; 106 | aes.FeedbackSize = AesBlockSize; 107 | aes.Padding = padding; 108 | aes.Key = key; 109 | aes.IV = iv; 110 | 111 | return aes; 112 | } 113 | 114 | /// 115 | /// Generates an AES key. 116 | /// 117 | /// 118 | /// The key size of the Aes encryption must be 128, 192 or 256 bits. 119 | /// Please check https://blogs.msdn.microsoft.com/shawnfa/2006/10/09/the-differences-between-rijndael-and-aes/ for more informations. 120 | /// 121 | /// AES Key size 122 | /// 123 | public static AesKeyInfo GenerateKey(AesKeySize keySize) 124 | { 125 | var aes = Aes.Create(); 126 | 127 | aes.KeySize = (int)keySize; 128 | aes.BlockSize = AesBlockSize; 129 | 130 | aes.GenerateKey(); 131 | aes.GenerateIV(); 132 | 133 | return new AesKeyInfo(aes.Key, aes.IV); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.DataEncryption/ModelBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Infrastructure; 3 | using Microsoft.EntityFrameworkCore.Metadata; 4 | using Microsoft.EntityFrameworkCore.Metadata.Internal; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using SoftFluent.EntityFrameworkCore.DataEncryption.Internal; 7 | using System; 8 | using System.Collections.Generic; 9 | using SoftFluent.ComponentModel.DataAnnotations; 10 | using System.Linq; 11 | using System.Reflection; 12 | 13 | namespace SoftFluent.EntityFrameworkCore.DataEncryption; 14 | 15 | /// 16 | /// Provides extensions for the . 17 | /// 18 | public static class ModelBuilderExtensions 19 | { 20 | /// 21 | /// Enables encryption on this model using an encryption provider. 22 | /// 23 | /// 24 | /// The instance. 25 | /// 26 | /// 27 | /// The to use, if any. 28 | /// 29 | /// 30 | /// The updated . 31 | /// 32 | public static ModelBuilder UseEncryption(this ModelBuilder modelBuilder, IEncryptionProvider encryptionProvider) 33 | { 34 | if (modelBuilder is null) 35 | { 36 | throw new ArgumentNullException(nameof(modelBuilder)); 37 | } 38 | 39 | if (encryptionProvider is null) 40 | { 41 | throw new ArgumentNullException(nameof(encryptionProvider)); 42 | } 43 | 44 | foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) 45 | { 46 | IEnumerable encryptedProperties = GetEntityEncryptedProperties(entityType); 47 | 48 | foreach (EncryptedProperty encryptedProperty in encryptedProperties) 49 | { 50 | #pragma warning disable EF1001 // Internal EF Core API usage. 51 | if (encryptedProperty.Property.FindAnnotation(CoreAnnotationNames.ValueConverter) is not null) 52 | { 53 | continue; 54 | } 55 | #pragma warning restore EF1001 // Internal EF Core API usage. 56 | 57 | ValueConverter converter = GetValueConverter(encryptedProperty.Property.ClrType, encryptionProvider, encryptedProperty.StorageFormat); 58 | 59 | if (converter != null) 60 | { 61 | encryptedProperty.Property.SetValueConverter(converter); 62 | } 63 | } 64 | } 65 | 66 | return modelBuilder; 67 | } 68 | 69 | private static ValueConverter GetValueConverter(Type propertyType, IEncryptionProvider encryptionProvider, StorageFormat storageFormat) 70 | { 71 | if (propertyType == typeof(string)) 72 | { 73 | return storageFormat switch 74 | { 75 | StorageFormat.Default or StorageFormat.Base64 => new EncryptionConverter(encryptionProvider, StorageFormat.Base64), 76 | StorageFormat.Binary => new EncryptionConverter(encryptionProvider, StorageFormat.Binary), 77 | _ => throw new NotImplementedException() 78 | }; 79 | } 80 | else if (propertyType == typeof(byte[])) 81 | { 82 | return storageFormat switch 83 | { 84 | StorageFormat.Default or StorageFormat.Binary => new EncryptionConverter(encryptionProvider, StorageFormat.Binary), 85 | StorageFormat.Base64 => new EncryptionConverter(encryptionProvider, StorageFormat.Base64), 86 | _ => throw new NotImplementedException() 87 | }; 88 | } 89 | 90 | throw new NotImplementedException($"Type {propertyType.Name} does not support encryption."); 91 | } 92 | 93 | private static IEnumerable GetEntityEncryptedProperties(IMutableEntityType entity) 94 | { 95 | return entity.GetProperties() 96 | .Select(x => EncryptedProperty.Create(x)) 97 | .Where(x => x is not null); 98 | } 99 | 100 | internal class EncryptedProperty 101 | { 102 | public IMutableProperty Property { get; } 103 | 104 | public StorageFormat StorageFormat { get; } 105 | 106 | private EncryptedProperty(IMutableProperty property, StorageFormat storageFormat) 107 | { 108 | Property = property; 109 | StorageFormat = storageFormat; 110 | } 111 | 112 | public static EncryptedProperty Create(IMutableProperty property) 113 | { 114 | StorageFormat? storageFormat = null; 115 | 116 | var encryptedAttribute = property.PropertyInfo?.GetCustomAttribute(false); 117 | 118 | if (encryptedAttribute != null) 119 | { 120 | storageFormat = encryptedAttribute.Format; 121 | } 122 | 123 | IAnnotation encryptedAnnotation = property.FindAnnotation(PropertyAnnotations.IsEncrypted); 124 | 125 | if (encryptedAnnotation != null && (bool)encryptedAnnotation.Value == true) 126 | { 127 | storageFormat = (StorageFormat)property.FindAnnotation(PropertyAnnotations.StorageFormat)?.Value; 128 | } 129 | 130 | return storageFormat.HasValue ? new EncryptedProperty(property, storageFormat.Value) : null; 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/PropertyBuilderExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using SoftFluent.ComponentModel.DataAnnotations; 6 | using SoftFluent.EntityFrameworkCore.DataEncryption; 7 | using SoftFluent.EntityFrameworkCore.DataEncryption.Internal; 8 | using SoftFluent.EntityFrameworkCore.DataEncryption.Providers; 9 | using SoftFluent.EntityFrameworkCore.DataEncryption.Test.Context; 10 | using System; 11 | using System.Linq; 12 | using Xunit; 13 | 14 | namespace SoftFluent.EntityFrameworkCore.Encryption.Test; 15 | 16 | public class PropertyBuilderExtensionsTest 17 | { 18 | private static readonly Faker _faker = new(); 19 | 20 | [Fact] 21 | public void PropertyBuilderShouldNeverBeNullTest() 22 | { 23 | Assert.Throws(() => PropertyBuilderExtensions.IsEncrypted(null)); 24 | } 25 | 26 | [Fact] 27 | public void PropertyShouldHaveEncryptionAnnotationsTest() 28 | { 29 | AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(AesKeySize.AES256Bits); 30 | var provider = new AesProvider(encryptionKeyInfo.Key, encryptionKeyInfo.IV); 31 | 32 | string name = _faker.Name.FullName(); 33 | byte[] bytes = _faker.Random.Bytes(_faker.Random.Int(10, 30)); 34 | 35 | UserEntity user = new() 36 | { 37 | Name = name, 38 | NameAsBytes = name, 39 | ExtraData = bytes, 40 | ExtraDataAsBytes = bytes, 41 | EmptyString = "" 42 | }; 43 | 44 | using var contextFactory = new DatabaseContextFactory(); 45 | using (var context = contextFactory.CreateContext(provider)) 46 | { 47 | Assert.NotNull(context); 48 | 49 | IEntityType entityType = context.GetUserEntityType(); 50 | Assert.NotNull(entityType); 51 | 52 | AssertPropertyAnnotations(entityType.GetProperty(nameof(UserEntity.Name)), true, StorageFormat.Default); 53 | AssertPropertyAnnotations(entityType.GetProperty(nameof(UserEntity.NameAsBytes)), true, StorageFormat.Binary); 54 | AssertPropertyAnnotations(entityType.GetProperty(nameof(UserEntity.ExtraData)), true, StorageFormat.Base64); 55 | AssertPropertyAnnotations(entityType.GetProperty(nameof(UserEntity.ExtraDataAsBytes)), true, StorageFormat.Binary); 56 | AssertPropertyAnnotations(entityType.GetProperty(nameof(UserEntity.Id)), false, StorageFormat.Default); 57 | AssertPropertyAnnotations(entityType.GetProperty(nameof(UserEntity.EmptyString)), true, StorageFormat.Base64); 58 | 59 | context.Users.Add(user); 60 | context.SaveChanges(); 61 | } 62 | 63 | using (var context = contextFactory.CreateContext(provider)) 64 | { 65 | UserEntity u = context.Users.First(); 66 | 67 | Assert.NotNull(u); 68 | Assert.Equal(name, u.Name); 69 | Assert.Equal(name, u.NameAsBytes); 70 | Assert.Equal(bytes, u.ExtraData); 71 | Assert.Equal(bytes, u.ExtraDataAsBytes); 72 | Assert.Null(u.EmptyString); 73 | } 74 | } 75 | 76 | private static void AssertPropertyAnnotations(IProperty property, bool shouldBeEncrypted, StorageFormat expectedStorageFormat) 77 | { 78 | Assert.NotNull(property); 79 | 80 | IAnnotation encryptedAnnotation = property.FindAnnotation(PropertyAnnotations.IsEncrypted); 81 | 82 | if (shouldBeEncrypted) 83 | { 84 | Assert.NotNull(encryptedAnnotation); 85 | Assert.True((bool)encryptedAnnotation.Value); 86 | 87 | IAnnotation formatAnnotation = property.FindAnnotation(PropertyAnnotations.StorageFormat); 88 | Assert.NotNull(formatAnnotation); 89 | Assert.Equal(expectedStorageFormat, formatAnnotation.Value); 90 | } 91 | else 92 | { 93 | Assert.Null(encryptedAnnotation); 94 | Assert.Null(property.FindAnnotation(PropertyAnnotations.StorageFormat)); 95 | } 96 | } 97 | 98 | private class UserEntity 99 | { 100 | public int Id { get; set; } 101 | 102 | // Encrypted as default (Base64) 103 | public string Name { get; set; } 104 | 105 | // Encrypted as raw byte array. 106 | public string NameAsBytes { get; set; } 107 | 108 | // Encrypted as Base64 string 109 | public byte[] ExtraData { get; set; } 110 | 111 | // Encrypted as raw byte array. 112 | public byte[] ExtraDataAsBytes { get; set; } 113 | 114 | // Encrypt as Base64 string, but will be empty. 115 | public string EmptyString { get; set; } 116 | } 117 | 118 | private class FluentDbContext : DbContext 119 | { 120 | private readonly IEncryptionProvider _encryptionProvider; 121 | 122 | public DbSet Users { get; set; } 123 | 124 | public FluentDbContext(DbContextOptions options) 125 | : base(options) 126 | { } 127 | 128 | public FluentDbContext(DbContextOptions options, IEncryptionProvider encryptionProvider) 129 | : base(options) 130 | { 131 | _encryptionProvider = encryptionProvider; 132 | } 133 | 134 | protected override void OnModelCreating(ModelBuilder modelBuilder) 135 | { 136 | var userEntityBuilder = modelBuilder.Entity(); 137 | 138 | userEntityBuilder.HasKey(x => x.Id); 139 | userEntityBuilder.Property(x => x.Id).IsRequired().ValueGeneratedOnAdd(); 140 | userEntityBuilder.Property(x => x.Name).IsRequired().IsEncrypted(); 141 | userEntityBuilder.Property(x => x.NameAsBytes).IsRequired().HasColumnType("BLOB").IsEncrypted(StorageFormat.Binary); 142 | userEntityBuilder.Property(x => x.ExtraData).IsRequired().HasColumnType("TEXT").IsEncrypted(StorageFormat.Base64); 143 | userEntityBuilder.Property(x => x.ExtraDataAsBytes).IsRequired().HasColumnType("BLOB").IsEncrypted(StorageFormat.Binary); 144 | userEntityBuilder.Property(x => x.EmptyString).IsRequired(false).HasColumnType("TEXT").IsEncrypted(StorageFormat.Base64); 145 | 146 | modelBuilder.UseEncryption(_encryptionProvider); 147 | } 148 | 149 | public IEntityType GetUserEntityType() => Model.FindEntityType(typeof(UserEntity)); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EntityFrameworkCore.DataEncryption 2 | 3 | [![.NET](https://github.com/SoftFluent/EntityFrameworkCore.DataEncryption/actions/workflows/build.yml/badge.svg)](https://github.com/SoftFluent/EntityFrameworkCore.DataEncryption/actions/workflows/build.yml) 4 | [![Nuget](https://img.shields.io/nuget/v/EntityFrameworkCore.DataEncryption.svg)](https://www.nuget.org/packages/EntityFrameworkCore.DataEncryption) 5 | [![Nuget Downloads](https://img.shields.io/nuget/dt/EntityFrameworkCore.DataEncryption)](https://www.nuget.org/packages/EntityFrameworkCore.DataEncryption) 6 | 7 | `EntityFrameworkCore.DataEncryption` is a [Microsoft Entity Framework Core](https://github.com/aspnet/EntityFrameworkCore) extension to add support of encrypted fields using built-in or custom encryption providers. 8 | 9 | ## Disclaimer 10 | 11 |

This project is maintained by SoftFluent


12 | 13 | This library has been developed initialy for a personal project of mine which suits my use case. It provides a simple way to encrypt column data. 14 | 15 | I **do not** take responsability if you use/deploy this in a production environment and loose your encryption key or corrupt your data. 16 | 17 | ## How to install 18 | 19 | Install the package from [NuGet](https://www.nuget.org/) or from the `Package Manager Console` : 20 | ```powershell 21 | PM> Install-Package EntityFrameworkCore.DataEncryption 22 | ``` 23 | 24 | ## Supported types 25 | 26 | | Type | Default storage type | 27 | |------|----------------------| 28 | | `string` | Base64 string | 29 | | `byte[]` | BINARY | 30 | 31 | ## Built-in providers 32 | 33 | | Name | Class | Extra | 34 | |------|-------|-------| 35 | | [AES](https://learn.microsoft.com/en-US/dotnet/api/system.security.cryptography.aes?view=net-6.0) | [AesProvider](https://github.com/SoftFluent/EntityFrameworkCore.DataEncryption/blob/main/src/EntityFrameworkCore.DataEncryption/Providers/AesProvider.cs) | Can use a 128bits, 192bits or 256bits key | 36 | 37 | ## How to use 38 | 39 | `EntityFrameworkCore.DataEncryption` supports 2 differents initialization methods: 40 | * Attribute 41 | * Fluent configuration 42 | 43 | Depending on the initialization method you will use, you will need to decorate your `string` or `byte[]` properties of your entities with the `[Encrypted]` attribute or use the fluent `IsEncrypted()` method in your model configuration process. 44 | To use an encryption provider on your EF Core model, and enable the encryption on the `ModelBuilder`. 45 | 46 | ### Example with `AesProvider` and attribute 47 | 48 | ```csharp 49 | public class UserEntity 50 | { 51 | public int Id { get; set; } 52 | 53 | [Encrypted] 54 | public string Username { get; set; } 55 | 56 | [Encrypted] 57 | public string Password { get; set; } 58 | 59 | public int Age { get; set; } 60 | } 61 | 62 | public class DatabaseContext : DbContext 63 | { 64 | // Get key and IV from a Base64String or any other ways. 65 | // You can generate a key and IV using "AesProvider.GenerateKey()" 66 | private readonly byte[] _encryptionKey = ...; 67 | private readonly byte[] _encryptionIV = ...; 68 | private readonly IEncryptionProvider _provider; 69 | 70 | public DbSet Users { get; set; } 71 | 72 | public DatabaseContext(DbContextOptions options) 73 | : base(options) 74 | { 75 | _provider = new AesProvider(this._encryptionKey, this._encryptionIV); 76 | } 77 | 78 | protected override void OnModelCreating(ModelBuilder modelBuilder) 79 | { 80 | modelBuilder.UseEncryption(_provider); 81 | } 82 | } 83 | ``` 84 | The code bellow creates a new [`AesProvider`](https://github.com/SoftFluent/EntityFrameworkCore.DataEncryption/blob/main/src/EntityFrameworkCore.DataEncryption/Providers/AesProvider.cs) and gives it to the current model. It will encrypt every `string` fields of your model that has the `[Encrypted]` attribute when saving changes to database. As for the decrypt process, it will be done when reading the `DbSet` of your `DbContext`. 85 | 86 | ### Example with `AesProvider` and fluent configuration 87 | 88 | ```csharp 89 | public class UserEntity 90 | { 91 | public int Id { get; set; } 92 | public string Username { get; set; } 93 | public string Password { get; set; } 94 | public int Age { get; set; } 95 | } 96 | 97 | public class DatabaseContext : DbContext 98 | { 99 | // Get key and IV from a Base64String or any other ways. 100 | // You can generate a key and IV using "AesProvider.GenerateKey()" 101 | private readonly byte[] _encryptionKey = ...; 102 | private readonly byte[] _encryptionIV = ...; 103 | private readonly IEncryptionProvider _provider; 104 | 105 | public DbSet Users { get; set; } 106 | 107 | public DatabaseContext(DbContextOptions options) 108 | : base(options) 109 | { 110 | _provider = new AesProvider(this._encryptionKey, this._encryptionIV); 111 | } 112 | 113 | protected override void OnModelCreating(ModelBuilder modelBuilder) 114 | { 115 | // Entities builder *MUST* be called before UseEncryption(). 116 | var userEntityBuilder = modelBuilder.Entity(); 117 | 118 | userEntityBuilder.Property(x => x.Username).IsRequired().IsEncrypted(); 119 | userEntityBuilder.Property(x => x.Password).IsRequired().IsEncrypted(); 120 | 121 | modelBuilder.UseEncryption(_provider); 122 | } 123 | } 124 | ``` 125 | 126 | ## Create an encryption provider 127 | 128 | `EntityFrameworkCore.DataEncryption` gives the possibility to create your own encryption providers. To do so, create a new class and make it inherit from `IEncryptionProvider`. You will need to implement the `Encrypt(string)` and `Decrypt(string)` methods. 129 | 130 | ```csharp 131 | public class MyCustomEncryptionProvider : IEncryptionProvider 132 | { 133 | public byte[] Encrypt(byte[] input) 134 | { 135 | // Encrypt the given input and return the encrypted data as a byte[]. 136 | } 137 | 138 | public byte[] Decrypt(byte[] input) 139 | { 140 | // Decrypt the given input and return the decrypted data as a byte[]. 141 | } 142 | } 143 | ``` 144 | 145 | To use it, simply create a new `MyCustomEncryptionProvider` in your `DbContext` and pass it to the `UseEncryption` method: 146 | ```csharp 147 | public class DatabaseContext : DbContext 148 | { 149 | private readonly IEncryptionProvider _provider; 150 | 151 | public DatabaseContext(DbContextOptions options) 152 | : base(options) 153 | { 154 | _provider = new MyCustomEncryptionProvider(); 155 | } 156 | 157 | protected override void OnModelCreating(ModelBuilder modelBuilder) 158 | { 159 | modelBuilder.UseEncryption(_provider); 160 | } 161 | } 162 | ``` 163 | 164 | ## Thanks 165 | 166 | I would like to thank all the people that supports and contributes to the project and helped to improve the library. :smile: 167 | 168 | ## Credits 169 | 170 | Package Icon : from [Icons8](https://icons8.com/) 171 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | # ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true 235 | **/wwwroot/lib/ 236 | 237 | # RIA/Silverlight projects 238 | Generated_Code/ 239 | 240 | # Backup & report files from converting an old project file 241 | # to a newer Visual Studio version. Backup files are not needed, 242 | # because we have git ;-) 243 | _UpgradeReport_Files/ 244 | Backup*/ 245 | UpgradeLog*.XML 246 | UpgradeLog*.htm 247 | ServiceFabricBackup/ 248 | *.rptproj.bak 249 | 250 | # SQL Server files 251 | *.mdf 252 | *.ldf 253 | *.ndf 254 | 255 | # Business Intelligence projects 256 | *.rdl.data 257 | *.bim.layout 258 | *.bim_*.settings 259 | *.rptproj.rsuser 260 | *- Backup*.rdl 261 | 262 | # Microsoft Fakes 263 | FakesAssemblies/ 264 | 265 | # GhostDoc plugin setting file 266 | *.GhostDoc.xml 267 | 268 | # Node.js Tools for Visual Studio 269 | .ntvs_analysis.dat 270 | node_modules/ 271 | 272 | # Visual Studio 6 build log 273 | *.plg 274 | 275 | # Visual Studio 6 workspace options file 276 | *.opt 277 | 278 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 279 | *.vbw 280 | 281 | # Visual Studio LightSwitch build output 282 | **/*.HTMLClient/GeneratedArtifacts 283 | **/*.DesktopClient/GeneratedArtifacts 284 | **/*.DesktopClient/ModelManifest.xml 285 | **/*.Server/GeneratedArtifacts 286 | **/*.Server/ModelManifest.xml 287 | _Pvt_Extensions 288 | 289 | # Paket dependency manager 290 | .paket/paket.exe 291 | paket-files/ 292 | 293 | # FAKE - F# Make 294 | .fake/ 295 | 296 | # JetBrains Rider 297 | .idea/ 298 | *.sln.iml 299 | 300 | # CodeRush personal settings 301 | .cr/personal 302 | 303 | # Python Tools for Visual Studio (PTVS) 304 | __pycache__/ 305 | *.pyc 306 | 307 | # Cake - Uncomment if you are using it 308 | # tools/** 309 | # !tools/packages.config 310 | 311 | # Tabs Studio 312 | *.tss 313 | 314 | # Telerik's JustMock configuration file 315 | *.jmconfig 316 | 317 | # BizTalk build output 318 | *.btp.cs 319 | *.btm.cs 320 | *.odx.cs 321 | *.xsd.cs 322 | 323 | # OpenCover UI analysis results 324 | OpenCover/ 325 | 326 | # Azure Stream Analytics local run output 327 | ASALocalRun/ 328 | 329 | # MSBuild Binary and Structured Log 330 | *.binlog 331 | 332 | # NVidia Nsight GPU debugger configuration file 333 | *.nvuser 334 | 335 | # MFractors (Xamarin productivity tool) working folder 336 | .mfractor/ 337 | 338 | # Local History for Visual Studio 339 | .localhistory/ 340 | 341 | # BeatPulse healthcheck temp database 342 | healthchecksdb 343 | 344 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 345 | MigrationBackup/ -------------------------------------------------------------------------------- /test/EntityFrameworkCore.DataEncryption.Test/Providers/AesProviderTest.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using Microsoft.EntityFrameworkCore; 3 | using SoftFluent.EntityFrameworkCore.DataEncryption.Providers; 4 | using SoftFluent.EntityFrameworkCore.DataEncryption.Test.Context; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using Xunit; 9 | 10 | namespace SoftFluent.EntityFrameworkCore.DataEncryption.Test.Providers; 11 | 12 | public class AesProviderTest 13 | { 14 | private static readonly Faker _faker = new(); 15 | 16 | [Fact] 17 | public void CreateAesProviderWithoutKeyTest() 18 | { 19 | Assert.Throws(() => new AesProvider(null, null)); 20 | } 21 | 22 | [Fact] 23 | public void CreateAesProviderWithoutInitializationVectorTest() 24 | { 25 | Assert.Throws(() => new AesProvider(Array.Empty(), null)); 26 | } 27 | 28 | [Fact] 29 | public void EncryptNullOrEmptyDataTest() 30 | { 31 | AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(AesKeySize.AES256Bits); 32 | var provider = new AesProvider(encryptionKeyInfo.Key, encryptionKeyInfo.IV); 33 | 34 | Assert.Null(provider.Encrypt(null)); 35 | Assert.Null(provider.Encrypt(Array.Empty())); 36 | } 37 | 38 | [Fact] 39 | public void DecryptNullOrEmptyDataTest() 40 | { 41 | AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(AesKeySize.AES256Bits); 42 | var provider = new AesProvider(encryptionKeyInfo.Key, encryptionKeyInfo.IV); 43 | 44 | Assert.Null(provider.Decrypt(null)); 45 | Assert.Null(provider.Decrypt(Array.Empty())); 46 | } 47 | 48 | [Theory] 49 | [InlineData(AesKeySize.AES128Bits)] 50 | [InlineData(AesKeySize.AES192Bits)] 51 | [InlineData(AesKeySize.AES256Bits)] 52 | public void EncryptDecryptByteArrayTest(AesKeySize keySize) 53 | { 54 | byte[] input = _faker.Random.Bytes(_faker.Random.Int(10, 30)); 55 | AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize); 56 | var provider = new AesProvider(encryptionKeyInfo.Key, encryptionKeyInfo.IV); 57 | 58 | byte[] encryptedData = provider.Encrypt(input); 59 | Assert.NotNull(encryptedData); 60 | 61 | byte[] decryptedData = provider.Decrypt(encryptedData); 62 | Assert.NotNull(decryptedData); 63 | 64 | Assert.Equal(input, decryptedData); 65 | } 66 | 67 | [Theory] 68 | [InlineData(AesKeySize.AES128Bits)] 69 | [InlineData(AesKeySize.AES192Bits)] 70 | [InlineData(AesKeySize.AES256Bits)] 71 | public void GenerateAesKeyTest(AesKeySize keySize) 72 | { 73 | AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(keySize); 74 | 75 | Assert.NotNull(encryptionKeyInfo.Key); 76 | Assert.NotNull(encryptionKeyInfo.IV); 77 | Assert.Equal((int)keySize / 8, encryptionKeyInfo.Key.Length); 78 | } 79 | 80 | [Theory] 81 | [InlineData(AesKeySize.AES128Bits)] 82 | [InlineData(AesKeySize.AES192Bits)] 83 | [InlineData(AesKeySize.AES256Bits)] 84 | public void CompareTwoAesKeysInstancesTest(AesKeySize keySize) 85 | { 86 | AesKeyInfo encryptionKeyInfo1 = AesProvider.GenerateKey(keySize); 87 | AesKeyInfo encryptionKeyInfo2 = AesProvider.GenerateKey(keySize); 88 | AesKeyInfo encryptionKeyInfoCopy = encryptionKeyInfo1; 89 | 90 | Assert.NotNull(encryptionKeyInfo1.Key); 91 | Assert.NotNull(encryptionKeyInfo1.IV); 92 | Assert.NotNull(encryptionKeyInfo2.Key); 93 | Assert.NotNull(encryptionKeyInfo2.IV); 94 | Assert.True(encryptionKeyInfo1 == encryptionKeyInfoCopy); 95 | Assert.True(encryptionKeyInfo1.Equals(encryptionKeyInfoCopy)); 96 | Assert.True(encryptionKeyInfo1 != encryptionKeyInfo2); 97 | Assert.True(encryptionKeyInfo1.GetHashCode() != encryptionKeyInfo2.GetHashCode()); 98 | Assert.False(encryptionKeyInfo1.Equals(0)); 99 | } 100 | 101 | [Fact] 102 | public void EncryptUsingAes128Provider() 103 | { 104 | ExecuteAesEncryptionTest(AesKeySize.AES128Bits); 105 | } 106 | 107 | [Fact] 108 | public void EncryptUsingAes192Provider() 109 | { 110 | ExecuteAesEncryptionTest(AesKeySize.AES192Bits); 111 | } 112 | 113 | [Fact] 114 | public void EncryptUsingAes256Provider() 115 | { 116 | ExecuteAesEncryptionTest(AesKeySize.AES256Bits); 117 | } 118 | 119 | private static void ExecuteAesEncryptionTest(AesKeySize aesKeyType) where TContext : DatabaseContext 120 | { 121 | AesKeyInfo encryptionKeyInfo = AesProvider.GenerateKey(aesKeyType); 122 | var provider = new AesProvider(encryptionKeyInfo.Key, encryptionKeyInfo.IV); 123 | var author = new AuthorEntity("John", "Doe", 42) 124 | { 125 | Books = new List 126 | { 127 | new(name: _faker.Lorem.Sentence(2), 128 | numberOfPages: _faker.Random.Int(100, 300), 129 | content: _faker.Random.Bytes(_faker.Random.Int(5, 10)), 130 | summary: _faker.Random.Bytes(_faker.Random.Int(5, 10))), 131 | new(name: _faker.Lorem.Sentence(2), 132 | numberOfPages: _faker.Random.Int(100, 300), 133 | content: _faker.Random.Bytes(_faker.Random.Int(5, 10)), 134 | summary: _faker.Random.Bytes(_faker.Random.Int(5, 10))), 135 | } 136 | }; 137 | 138 | using var contextFactory = new DatabaseContextFactory(); 139 | 140 | // Save data to an encrypted database context 141 | using (var dbContext = contextFactory.CreateContext(provider)) 142 | { 143 | dbContext.Authors.Add(author); 144 | dbContext.SaveChanges(); 145 | } 146 | 147 | // Read decrypted data and compare with original data 148 | using (var dbContext = contextFactory.CreateContext(provider)) 149 | { 150 | AuthorEntity authorFromDb = dbContext.Authors.Include(x => x.Books).FirstOrDefault(); 151 | 152 | Assert.NotNull(authorFromDb); 153 | Assert.Equal(author.FirstName, authorFromDb.FirstName); 154 | Assert.Equal(author.LastName, authorFromDb.LastName); 155 | Assert.NotNull(authorFromDb.Books); 156 | Assert.NotEmpty(authorFromDb.Books); 157 | Assert.Equal(2, authorFromDb.Books.Count); 158 | 159 | foreach (var book in authorFromDb.Books) 160 | { 161 | BookEntity originalBook = author.Books.FirstOrDefault(x => x.Id == book.Id); 162 | 163 | Assert.NotNull(originalBook); 164 | Assert.Equal(originalBook.Name, book.Name); 165 | Assert.Equal(originalBook.Content, book.Content); 166 | Assert.Equal(originalBook.Summary, book.Summary); 167 | } 168 | } 169 | } 170 | 171 | public class Aes128EncryptedDatabaseContext : DatabaseContext 172 | { 173 | public Aes128EncryptedDatabaseContext(DbContextOptions options, IEncryptionProvider encryptionProvider = null) 174 | : base(options, encryptionProvider) { } 175 | } 176 | 177 | public class Aes192EncryptedDatabaseContext : DatabaseContext 178 | { 179 | public Aes192EncryptedDatabaseContext(DbContextOptions options, IEncryptionProvider encryptionProvider = null) 180 | : base(options, encryptionProvider) { } 181 | } 182 | 183 | public class Aes256EncryptedDatabaseContext : DatabaseContext 184 | { 185 | public Aes256EncryptedDatabaseContext(DbContextOptions options, IEncryptionProvider encryptionProvider = null) 186 | : base(options, encryptionProvider) { } 187 | } 188 | 189 | public class SimpleEncryptedDatabaseContext : DatabaseContext 190 | { 191 | public SimpleEncryptedDatabaseContext(DbContextOptions options, IEncryptionProvider encryptionProvider = null) 192 | : base(options, encryptionProvider) { } 193 | } 194 | } 195 | --------------------------------------------------------------------------------