How to encrypt and decrypt data in ASP.NET Core using Data Protection API. by info.odysseyx@gmail.com September 24, 2024 written by info.odysseyx@gmail.com September 24, 2024 0 comment 1 views 1 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. When you press the Encrypt button, the encrypted string will be displayed as shown below. To get the decrypted original text, copy the encrypted string, paste it into the text box and click the decrypt button. You should see the original decrypted string as shown below. 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 Share 0 FacebookTwitterPinterestEmail info.odysseyx@gmail.com previous post Implementing Route Summarization in Azure VMware Solution next post Governing data for GenAI with SharePoint Advanced Management You may also like Get to know Microsoft 365 Copilot in Microsoft OneDrive October 4, 2024 Connecting to Azure Cache for Redis with Entra ID in Azure Government October 4, 2024 Modern Charts in Microsoft Access is GA! October 4, 2024 Cowrie honeypot and its Integration with Microsoft Sentinel. October 4, 2024 Improved Accessibility ribbon in PowerPoint for Windows and Mac October 4, 2024 Introducing the Use Cases Mapper workbook October 4, 2024 Leave a Comment Cancel Reply Save my name, email, and website in this browser for the next time I comment.