Advertisement
Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Jun 15, 2021

Encrypt your database columns with EntityFramework & .NET Core

Автор:
Emre Kizildas
Источник:
Просмотров:
3019

Hi everyone, this article include encrypting your database columns with EntityFramework. Your database providers can be MSSQL or PostgreSQL.

Considering that some database columns contain confidential data, it is of great importance that the data is encrypted in case of capture of our database.

In this article, it will be ensured that your “string” type data is kept encrypted in the database and can be displayed automatically by decrypting the relevant data when you want to use it.

Let’s Create a Project

In this step, let’s create a simple console application regardless of the requirements of any architectural approach.

After naming the project, let’s create it by choosing the “.Net 5.0” version of the project.

Let’s Install NuGet Packages

Let’s install the following NuGet packages to use in our project:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.Tools
  • Npgsql.EntityFrameworkCore.PostgreSQL
  • EntityFrameworkCore.EncryptColumn

The .csproj file of the project will look like this:

Let’s Create Database Object and Table

Let’s create a folder named “Entity” in our project and create a class named “User” in it. You can create your “User” class as follows:

Then, in order to make this class a database table, let’s create a folder named “Context” in our project and create a class called “ExampleDbContext” inside it. This class should be created to inherit the “DbContext” class.

With some additional improvements, you can create a table named “Users” and automatically create the “ID” parameter in this table. Then, let’s apply our migration commands to make these codes into a table in the database.

Let’s run the “Add-Migration initialize” command over the “Package Manager Console”, then run the “update-database” command to make our database ready.

If the following error is received during these commands, a SQL script must be run:

CREATE TABLE IF NOT EXISTS "encryptexample"."__EFMigrationsHistory" (
"MigrationId" varchar(150) NOT NULL,
"ProductVersion" varchar(32) NOT NULL,
CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);

When you set up your database correctly, you should get the screenshot below:

Determining Columns to Encrypt and Database Configuration

You need to use attribute as below for the columns you want to keep the data encrypted on your database. The “EncryptColumn” parameter in the “EntityFrameworkCore.EncryptColumn.Attribute” class will be used.

After determining the columns to be encrypted in our table, we can configure the database.

  • A parameter is created by using the “IEncryptionProvider” interface in the “ExampleDbContext” class.
  • We determine our encryption key in the constructor method of the “ExampleDbContext” class. Then we create our encryption provider.
  • Finally, we indicate that we will use the encryption provider within the “OnModelCreating” method.

modelBuilder.UseEncryption(this._provider);

The display of the “ExampleDbContext” class will finally look like this:

Data Adding and Listing

Let’s add a row to the “Users” table in our database for testing purposes in the “Program.cs” class. Next, let’s list the user we added.

The console screen that appears when we run this program is as follows:

As you know, we defined the “IdentityNumber” and “EmailAddress” columns as encrypted. The image of these fields in the database is as follows:

You can now use the “EncryptColumn” attribute for the columns you want in your database, so that the relevant column is stored with encrypted data in the database.

From the link below to the source code of the project:

EntityFrameworkCore.EncryptColumn.Example

Похожее
Aug 24, 2022
Author: Jaydeep Patil
In this article, we will learn about global exception handling implementation using .NET Core 6 Web API step-by-step.Agenda Introduction Implementation of Global Exception HandlingPrerequisites Visual Studio 2022 .NET...
Apr 13
In this article, let’s learn about how to perform file upload in ASP.NET Core 6. The file for upload can be of any format like image (jpg, BMP, gif, etc), text file, XML file, CSV file, PDF file, etc. We...
Nov 7, 2020
Author: Rebai Hamida
IntroductionDuring this article, we will learn how to work with the microservice architecture patterns and Docker containers using the .NET Core 3 platform to build a distributed system.Monolithic vs Microservices ArchitectureBefore talking about Microservices, we need to understand the difference...
Jan 25
Author: Dev·edium
A deep dive into Ahead-of-Time (AOT) compilation for optimized performanceWhat is it?Traditionally, .NET languages like C# use Just-in-Time (JIT) compilation. In this process, the source code is initially compiled into Common Intermediate Language (CIL) code, a platform-agnostic code representation. Only...
Написать сообщение
Почта
Имя
*Сообщение


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban
GraphQL решает кучу проблем — рассказываем, за что мы его любим
Переход от монолита к микросервисам: история и практика
Развенчание мифа о собственной продуктивности программистов
Почему сеньоры ненавидят собеседования с кодингом, и что компании должны использовать вместо них
Проблема понимания существующего кода, или Как делать иногда [не] надо
Vite.js: что это и зачем нужно веб-разработчику
Экстремальное программирование: новые возможности
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Станут ли роботы причиной глобальной безработицы?
Performance review, ачивки и погоня за повышением грейда — что может причинить боль сотруднику IT-компании?
LinkedIn
Boosty
Donate to support the project
GitHub account
GitHub profile