top of page

Data Protection in ASP.NET Core

The data protection system is a set of cryptography APIs used by ASP.NET Core to encrypt data that must be handled by an untrusted third party.



Data protection API creates and manages a secrete key for encryption, it can be used by 3 types of users

  • Application and framework developers, who don't want to know how Data protection API and stack work and how it is configured, just want to pass the input and get output from API

  • System Admin and Developers, who don't want to store their secret file and keys on default path with default settings. So that nobody can easily track it. e.g. program default TEMP data should not store to '%AppData%' path (which is default path), ASP.NET Core has 'IDataProtectionBuilder' interface which allow us to change all default path and settings

For data protection, ASP.NET core support both encryption and hashing technique.


Using Data Protection in ASP.NET Core

Use of Data protection is really simple, just you need to import 'AspNetCore.DataProtection' and 'Extensions.DependencyInjection' namesapces, and to protect your data you need to use protect() method (To use protect() method we need to create data protector using data protection provider) that's it. we have done. Lets see how it works


Encryption using ASP.NET Core

Encryption needs a Key to encrypt data, but here, key is created and maintained by API itself, these keys are generated with the default lifespan of 90 days and stored at a secrete (maybe we call it as suitable) location. This Key is temporary, the data protection API is designed to secure short term data like Querystring, cookies etc. see below snippet

using System;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;

public class Program{
    public static void Main(string[] args)
    {
        //use data protection servicesvar SCollection = new ServiceCollection();

       //add protection services
        SCollection.AddDataProtection();
        var SerPro = SCollection.BuildServiceProvider();

        // create an instance of classfile using 'CreateInstance' methodvar instance = ActivatorUtilities.CreateInstance<ProClass>(SerPro);
        instance.getPutOut();
    }

    public class ProClass{
        IDataProtector _iPro;

        // the 'provider' parameter is provided by DI
        public ProClass(IDataProtectionProvider provider)
        {
            _iPro = provider.CreateProtector("ProClass");
        }

        public void getPutOut()
        {
            string input = "Hello World";

            // protect string
            string protectedString = _iPro.Protect(input);
           
            // protect string
            string unProtectedString = _iPro.Unprotect(protectedString);
        }
    }
}

//outputinput : "Hello World"protectedString : CfDJ8ICcgQwZZhlAlTZT....
unprotectedeString : "Hello World"

In above sample we have create a 'ServiceCollection' object which is used to create and add data protection services, then we create a instance of our class using 'CreateInstance' method, This method is exposed by 'ActivatorUtilities' class (which is a static helper class from 'Microsoft.Framework.DependencyInjection' namesapce, it has some inbuilt methods that are help to deal with constructor parameters) , finally we simply call 'Protect' and 'Unprotect' method

** Have you notice one thing here? We have pass a string to 'CreateProtector' method, Do you know what that string indicate? it is call 'purpose string' basically it is used to create a isolated environment, e.g. if we create a protector with a string 'ABC' and protect a data, it cannot be unprotect same data with a protector created with string 'XYZ', so it is again a step forward to make data more secure.


Hashing using ASP.NET Core

With the help of 'Microsoft.AspNetCore.Cryptography.KeyDerivation' package we can implement hashing using ASP.NET Core, it has 'Pbkdf2'method which uses 'PBKDF2 algorithm' to hashed a data. see below snippet to know how to secure data using hashing

using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
 
public class Program{
    public static void Main(string[] args)
    {
        string SimpleText = "myText";
 
        //Generate a 128-bit salt//**Salt: it is nothing but a random number
        byte[] Slt = new byte[128 / 8];
        using (var RandomNum = RandomNumberGenerator.Create())
        {
            RandomNum.GetBytes(Slt);
        }
 
        // Create 256-bit key using HMACSHA1 algorithm with 1000 iterations
        string secureHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
            password: SimpleText,
            salt: Slt,
            prf: KeyDerivationPrf.HMACSHA1,
            iterationCount: 1000,
            numBytesRequested: 256 / 8));

        System.IO.AppendAllText("D:\\hashed.txt", "HashedText : " + secureHash);
    }
}


Install the Microsoft.AspNetCore. DataProtection NuGet package

To work with the Data Protection API in ASP.NET Core, install the Microsoft.AspNetCore.DataProtection package from the NuGet package manager window in Visual Studio. Alternatively, you can install this package via the NuGet package manager console by entering the following command.

Install-Package Microsoft.AspNetCore.DataProtection -Version 2.2.0


Configure the Data Protection API in ASP.NET Core

The AddDataProtection extension method can be used to configure the Data Protection API. The following code snippet illustrates how this can be accomplished in the ConfigureServices method of the Startup class.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDataProtection();
        ...
        services.AddMvc().SetCompatibilityVersion
        (CompatibilityVersion.Version_2_2);
    }

If you would like to store the keys in the file system, here is how you would need to configure the Data Protection API:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDataProtection().PersistKeysToFileSystem
        (new DirectoryInfo(@"D:\IDG\Temp"));
    }

Note that the key is created and maintained by the Data Protection API and that these keys have a lifespan of 90 days by default. You can also specify a lifetime for your key. The following code snippet illustrates how this can be achieved.

public void ConfigureServices(IServiceCollection services)
    {
        services.ConfigureDataProtection(dp =>
        {
            dp.PersistKeysToFileSystem
             (new DirectoryInfo(@"D:\IDG\Temp"));
            dp.SetDefaultKeyLifetime(TimeSpan.FromDays(7));
        });
        ....
    }

You can even protect keys with a certificate or store the keys in Azure Key Vault. If you want to persist the keys in Azure Key Vault, you should configure the Data Protection API as shown in the code snippet given below.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDataProtection()
            .PersistKeysToAzureBlobStorage(new Uri(
             "Specify the Uri here"))
            .ProtectKeysWithAzureKeyVault
            ("keyIdentifier", "clientId", "clientSecret");
    }


Resource: infoworld, code-maze


The Tech Platform

www.thetechplatform.com

0 comments
bottom of page