Home NewsX How to encrypt and decrypt data in ASP.NET Core using Data Protection API.

How to encrypt and decrypt data in ASP.NET Core using Data Protection API.

by info.odysseyx@gmail.com
0 comment 1 views


In today’s digital world, protecting sensitive information is more important than ever. With ASP.NET Core, you can store configuration settings in appsettings.json. However, hardcoding sensitive data, such as connection strings or API keys, in plain text can expose your application to serious risks.

ASP.NET Core has native support for encryption. Data Protection API. This can be used to protect sensitive information. The Data Protection API in ASP.NET Core makes it easy to encrypt and decrypt sensitive data such as user information and configuration settings. This article guides you through how to use the ASP.NET Core Data Protection API to encrypt and decrypt sensitive information in your application.

ASP.NET Core includes: Data Protection API Basically, unless you store your keys externally (like Azure or Redis), you don’t need to install any additional packages. Here are the detailed steps to use this package: Data Protection API To protect sensitive information.

Step 1: Create a service for data encryption

First, create a service class that performs the encryption and decryption operations using IDataProtector. This separates the encryption/decryption logic from the controller, 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

Register the EncryptionService in your Startup.cs file so that it can be injected into 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();
            services.AddControllersWithViews();
        }

    }
}

Step 3: Calling the encryption/decryption method from the controller

Now that we have our EncryptionService set up, let’s call these methods from our 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 HTTP requests from forms, UI pages, or API clients like Postman.

Here is a sample HTML form I used for testing purposes:




The first form posts sensitive data to EncryptData and then returns an encrypted string.

The second form posts the encrypted data to DecryptData and then returns the original plaintext.

Now finally run the application and enter the test data to be encrypted as shown below.

Hariomdubai_0-1727024348746.png

When you press the Encrypt button, the encrypted string will be displayed as shown below.

Hariomdubey_0-1727025345538.png

To get the decrypted original text, copy the encrypted string, paste it into the text box and click the decrypt button.

Hariomdubey_2-1727024615095.png

You should see the original decrypted string as shown 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. Following the steps above, you can easily integrate encryption into your controllers and services, making your application more secure without too much complexity.

memo: The solution described in this article can be applied to a single web server setup. If you are working with a web farm, additional steps are required.





Source link

You may also like

Leave a Comment

Our Company

Welcome to OdysseyX, your one-stop destination for the latest news and opportunities across various domains.

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

Laest News

@2024 – All Right Reserved. Designed and Developed by OdysseyX