Encrypting and Decrypting sensitive Information in ASP.NET Core
Published Sep 24 2024 01:23 PM 1,785 Views
Microsoft

In today’s digital landscape, securing sensitive information is more critical than ever. If you're using ASP.NET Core, you might store configuration settings in appsettings.json. However, hardcoding sensitive data like connection strings or API keys in plain text can expose your application to serious risks.

 

ASP.NET Core has built-in support for encryption through its Data Protection API. This can be used to secure sensitive information. The Data Protection API in ASP.NET Core allows you to easily encrypt and decrypt sensitive data, such as user information, and configuration settings. This article will guide you through encrypting and decrypting sensitive information using ASP.NET Core Data Protection API in your application.

 

ASP.NET Core includes the Data Protection API by default. You do not need to install additional packages unless you're storing keys externally (like Azure or Redis). Below are detailed steps for using this Data Protection API to protect sensitive information.

 

Step 1: Create a Service for Data Encryption

First, create a service class that uses IDataProtector to perform the encryption and decryption tasks. This allows you to separate the logic for encryption/decryption from your controllers, promoting cleaner code and reusability.

 

 

using Microsoft.AspNetCore.DataProtection;

public class EncryptionService
{
    private readonly IDataProtector _protector;

    // Constructor to initialize the IDataProtector using dependency injection
    public EncryptionService(IDataProtectionProvider provider)
    {
        // 'MyPurpose' is a unique string that ensures different protection policies for different purposes
        _protector = provider.CreateProtector("MyPurpose");
    }

    // Method to encrypt plain text data
    public string EncryptData(string plainText)
    {
        return _protector.Protect(plainText);
    }

    // Method to decrypt the encrypted data
    public string DecryptData(string encryptedData)
    {
        try
        {
            return _protector.Unprotect(encryptedData);
        }
        catch (Exception ex)
        {
            // If decryption fails (e.g., data is tampered or invalid), handle the exception
            return $"Decryption failed: {ex.Message}";
        }
    }
}

 

 

Step 2: Register the Encryption Service in Startup.cs

In the Startup.cs file, register the EncryptionService so that it can be injected into your controllers or other services.

 

 

using Microsoft.AspNetCore.DataProtection;

namespace CoreWebApplication1
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            // Register the Data Protection service
            services.AddDataProtection()  
            .PersistKeysToFileSystem(new DirectoryInfo(@"C:\DataProtectionKeys"))  // Optional: Specify where to store keys
            .SetApplicationName("MyApp");

            // Register the EncryptionService for dependency injection
            services.AddScoped<EncryptionService>();
            services.AddControllersWithViews();
        }

    }
}

 

 

Step 3: Call Encryption/Decryption Methods from a Controller

Now that we have the EncryptionService set up, let's call these methods from a Controller.

 

 

using CoreWebApplication1.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.DataProtection;


namespace CoreWebApplication1.Controllers
{
    public class HomeController : Controller
    {
        private readonly EncryptionService _encryptionService;
       
        public HomeController(EncryptionService encryptionService)
        {
            _encryptionService = encryptionService;
        }
        
        public IActionResult Index()
        {            
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        // Action to encrypt sensitive data
        [HttpPost]
        public IActionResult EncryptData(string sensitiveData)
        {
            // Call the EncryptData method to encrypt the input
            var encryptedData = _encryptionService.EncryptData(sensitiveData);

            // For demonstration purposes, return the encrypted data to the view
            return Content($"Encrypted data: {encryptedData}");
        }

        // Action to decrypt previously encrypted data
        [HttpPost]
        public IActionResult DecryptData(string encryptedData)
        {
            // Call the DecryptData method to decrypt the encrypted data
            var decryptedData = _encryptionService.DecryptData(encryptedData);

            // For demonstration purposes, return the decrypted data to the view
            return Content($"Decrypted data: {decryptedData}");
        }
        
    }
}

 

 

Step 4: Calling the Controller

You can now call these methods (EncryptData and DecryptData) via an HTTP request from a form, a UI page or even API clients like Postman.

 

Here is the Sample HTML Form for testing purposes:

 

<form method="post" action="/Home/EncryptData">
    <label for="data">Enter sensitive data to encrypt:</label>
    <input type="text" id="data" name="sensitiveData">
    <input type="submit" value="Encrypt">
</form>

<form method="post" action="/Home/DecryptData">
    <label for="data">Enter encrypted data to decrypt:</label>
    <input type="text" id="data" name="encryptedData">
    <input type="submit" value="Decrypt">
</form>

 

 

The first form posts sensitive data to EncryptData, which then returns the encrypted string.

The second form posts encrypted data to DecryptData, which then returns the original plain text.

 

Now, finally when running the application, and putting some test data to encrypt as below:

 

hariomdubey_0-1727024348746.png

 

After hitting the Encrypt button, you will see the encrypted string as below:

 

hariomdubey_0-1727025345538.png

 

To get the decrypted original text back, copy the encrypted string and put it in the textbox, and click on Decrypt button.

 

hariomdubey_2-1727024615095.png

 

you should see the original decrypted string as below:

 

hariomdubey_3-1727024665636.png

 

 

Conclusion:
With the Data Protection API, ASP.NET Core provides a powerful, built-in mechanism for encrypting and decrypting sensitive data. By following the above steps, you can easily integrate encryption into your controllers and services, making your applications more secure without adding too much complexity.

 

Note: Please be aware that the solution outlined in this article is applicable to a single web server setup. If you're working with a web farm, additional steps will be required.

 

Co-Authors
Version history
Last update:
‎Sep 24 2024 04:58 AM
Updated by: