How to use the Data Protection API in ASP.NET Core

Take advantage of the easy-to-use cryptographic API in ASP.NET Core to secure sensitive data in your applications.

5 cryptography and data protection
Getty Images

The Data protection stack in ASP.NET Core provides an easy-to-use cryptographic API for protecting data, including the necessary mechanisms for encryption and decryption. This article looks at how we can work with this API when building our ASP.NET Core applications.

Create an ASP.NET Core MVC project in Visual Studio

First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2017 or Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create. 
  7. In the “Create New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top.
  8. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. Click Create. 

Following these steps should create a new ASP.NET Core project in Visual Studio. We’ll use this project in the subsequent sections of this article.

The Data Protection API in ASP.NET Core takes advantage of both hashing and encryption for security. Before we proceed, let’s take a moment to understand these two concepts.

Encryption and hashing are not the same

Encryption and hashing are two important concepts related to security that are often used interchangeably, but incorrectly. Encryption is a technique of converting data from one form to another using a cryptographic algorithm. It is a two-way function as the data that has been encrypted can only be decrypted using a proper key. The encrypted data is known as cipher text. Encryption is by far the most effective way to secure data in today’s communication systems.

By contrast, hashing is a technique that generates a unique message digest from a string of text. It should be noted that the hashed data is always unique; you cannot produce the same hash value from different text. Further, it is almost impossible to get back the original text from the hashed value. So, while encryption is a two-way technique that includes both encryption and decryption of data using a key, hashing is a one-way technique that changes a string of plain text to a unique digest that cannot easily be reversed back to the original text.

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)

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)
    (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 =>
         (new DirectoryInfo(@"D:\IDG\Temp"));

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)
            .PersistKeysToAzureBlobStorage(new Uri(
             "Specify the Uri here"))
            ("keyIdentifier", "clientId", "clientSecret");

Encrypting data with the Data Protection API in ASP.NET Core

Now that the Data Protection API has been installed and configured in your project, you can take advantage of the API to protect data. To take advantage of the Data Protection API in the controller, you can use the following code.

public class HomeController : Controller
        IDataProtector _protector;
        public HomeController(IDataProtectionProvider provider)
            _protector = provider.CreateProtector(GetType().FullName);
        public IActionResult Index()
            TestModel testModel = new TestModel();
            var protectedData = _protector.Protect("Hello World");
            testModel.Data = protectedData;   
            //Write code here to persist the model to the db or to a file
            return View();
    //Other action methods

When you execute the application and set a breakpoint in the action method, you’ll be able to see that the data has been encrypted. core data protection IDG

The ASP.NET Core Data Protection API in action.

You can create a helper class to encrypt and decrypt data using the Data Protection API. The following code listing shows a reusable class that can be used for this purpose. Note how the key is being passed as the second argument to the Encrypt and Decrypt methods. This allows you to encrypt and decrypt data using your custom key.

public class DataProtectionHelper
        private readonly IDataProtectionProvider
        public DataProtectionHelper(IDataProtectionProvider
             _dataProtectionProvider = dataProtectionProvider;
        public string Encrypt(string textToEncrypt, string key)
             return _dataProtectionProvider.CreateProtector(key).
        public string Decrypt(string cipherText, string key)
             return _dataProtectionProvider.CreateProtector(key).

The Data Protection API is easy to use and flexible. It’s a good choice for encrypting data, such as query strings and cookies, that will be secured and persisted for only a short period of time. If you plan to use your cipher text (encrypted data) for a longer period, you might want to implement your own encryption and decryption logic.

Copyright © 2019 IDG Communications, Inc.