Take advantage of the easy-to-use cryptographic API in ASP.NET Core to secure sensitive data in your applications. Credit: 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Create. 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. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either. 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) { 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:IDGTemp")); } 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:IDGTemp")); 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"); } 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. 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 _dataProtectionProvider; public DataProtectionHelper(IDataProtectionProvider dataProtectionProvider) { _dataProtectionProvider = dataProtectionProvider; } public string Encrypt(string textToEncrypt, string key) { return _dataProtectionProvider.CreateProtector(key). Protect(textToEncrypt); } public string Decrypt(string cipherText, string key) { return _dataProtectionProvider.CreateProtector(key). Unprotect(cipherText); } } 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. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos