Today we are going to cover very interesting and inbuilt feature provided by Dot Net Core i.e DataProtection.

Data security is very important aspect of web application development to secure the client sensitive data. Dot Net core made it very easy  to secure data by encrypting it using in build Data Protection feature

To make the article more readable and simple i am dividing it into following mention point.

1 -Configuring the  Data Protection in Startup.cs file

2-Creating Data Protection using IDataProtectionProvider

3-Protecting(Encrypting) Data using IDataProtector

3-UnProtecting(Decryptiong) Data using IDataProtector

4-Protecting Data for Limited Time



Prerequisite-

1-Visual Studio-2017
2-Dot Net Core

1 -Configuring the  Data Protection in Startup.cs file
Configuring DataProtection is very simple we just need to configure AddDataProtection() in startup.cs as shown below.



2-Creating Data Protection using IDataProtectionProvider
once we are done with the required configuration on startup.cs we need to create the instance of protector by injecting the IDataProtectionProvider in the constructor of the controller .
To use the IDataProtectionProvider  we need to add reference of the Microsoft.AspNetCore.DataProtection. after adding the required reference we can create the protector instance as shown below.


The parameter provided to the constructor of CreateProtector() is called as Purpose String.
to know more about this please go through the official documentation here
3-Protecting(Encrypting) Data using IDataProtector
After creating the instance of the IDataProtector we can simply encrypt the data using the Protect() method  shown below


you will get the encrypted output like


4-UnProtecting(Decryptiong) Data using IDataProtector

Unprotecting is the reverse action of protecting here we need to provide encrypted input to the UnProtect() of the IDataProtector

4-Protecting Data for Limited Time

Protecting data for limited time is very simple we just need to invoke ToTimeLimitedDataProtector() on current instance of the IDataProtector. It will return an instance of ITimeLimitedDataProtector .once you get this instance you can use it like below code

if you try to decrypt the value after expiration time limit you will get en error .will show you in example.

           var bankaccount = "HJKG12345679";
           var timelimitProtector= dataProtector.ToTimeLimitedDataProtector();
           var encryptedresponse= timelimitProtector.Protect(bankaccount,lifetime:TimeSpan.FromMilliseconds(3000));

           Thread.Sleep(3000);

           var decryptedresponse= dataProtector.Unprotect(encryptedresponse);

In Above example i am simply setting up encryption lifetime to 3 second and in next line stopping thread for 3 second .After 3 second when i am trying to unprotect or decrypt the data i am getting the error as shown in below image.