Home > Back-end >  How to create EncryptColumn by Fluent Api on EF Core
How to create EncryptColumn by Fluent Api on EF Core

Time:10-20

There is a package that allows us to annotate a class with an EncryptColumn, in order to have a way of encrypting values on the SQL.

That approach demands an Attribute in the POCO Class, is there an alternative using the Fluent API of EF and configuring a certain Column as EncryptColumn?

CodePudding user response:

If you encrypt and decrypt in SQL-Server use this scenario :

Create database Encrypt_Test
GO
Create table Person(
     ID int not null identity
    ,FirstName Nvarchar(50) null
    ,LastName Nvarchar(50) null
    ,Phone  nvarchar(30) null
    )
-- insert sample
Insert into Person (FirstName,LastName,Phone)
    values(N'ALI',N'XSheet','09121212112')
          ,(N'SARA',N'Franki','09121313113')
          ,(N'ELI',N'Amiri','09121515115')

Create a master key for database and save safe:

Use Encrypt_Test
GO
CREATE MASTER KEY ENCRYPTION BY   
PASSWORD = 'asdfghjkl1`234567)(*&^%LKJHGF';

Check master key with this query :

Select   name
        ,principal_id                   
        ,symmetric_key_id               
        ,key_length                 
        ,key_algorithm              
        ,algorithm_desc             
        ,create_date                
        ,modify_date                
        ,key_guid                   
from sys.symmetric_keys

Create certificate :

CREATE CERTIFICATE PhoneNumber  
WITH SUBJECT = 'Customer Phone Numbers';

GO

CREATE SYMMETRIC KEY PhoneNumber_Key256 
WITH ALGORITHM = AES_256  
ENCRYPTION BY CERTIFICATE PhoneNumber; 

GO

ALTER TABLE Person   
ADD PhoneNumber varbinary(160);

Use OPEN SYMMETRIC for open encryption and read:

OPEN SYMMETRIC KEY PhoneNumber_Key256  
DECRYPTION BY CERTIFICATE PhoneNumber;  
GO  

SELECT  Phone
              ,PhoneNumber  AS 'Encrypted PhoneNumber'  
              ,CONVERT(nvarchar,DecryptByKey(PhoneNumber, 1 , HashBytes('SHA1', CONVERT(varbinary, Phone))))  AS 'Decrypted card number' 
FROM Person;  

reference

CodePudding user response:

I think you can use some 3rd party libraries for this one.

Examples

  1. https://www.nuget.org/packages/EntityFrameworkCore.EncryptColumn

  2. https://github.com/Eastrall/EntityFrameworkCore.DataEncryption

Thanks, Erandika

  • Related