Encrypt/Decrypt Query String in ASP.NET Core MVC




This blog is going to explain how to encrypt and decrypt query string or route data. Let us see with an example

For encryption and decryption .Net has IDataProtector interface, which provides data protection services. To use the interface, you have to add the Microsoft.AspNetCore.DataProtection namespace.

In the code below, the IDataProtector is injected through the HomeController constructor. In the EncryptValue action, the given input string is encrypted using the _dataProtector.Protect() method. It Cryptographically encrypts the plain text.  And in the DecryptValue action, the encrypted string is decrypted using the _dataProtector.Unprotect() method. It will return the plain protected text.

using Microsoft.AspNetCore.DataProtection;

   public class HomeController : Controller
    {
       private readonly IDataProtector _dataProtector;

        public HomeController(IDataProtectionProvider provider)
        {
            _dataProtector = provider.CreateProtector(GetType().FullName);
        }

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

        [HttpPost]
        public IActionResult EncryptValue(string inputText)
        {
            string encryptedId = _dataProtector.Protect(inputText);
            return RedirectToAction("DecryptValue","Home", new { encrypttxt= encryptedId });
        }

        public IActionResult DecryptValue(string encrypttxt)
        {
            string decryptedvalue = _dataProtector.Unprotect(encrypttxt);
            Tuple<string, string> tuple = new Tuple<string, string>(encrypttxt, decryptedvalue);
            return View("Decrypt", tuple);
        }
    }

The following is a Index page code. It has a textbox to enter value to encrypt text and a submit button to submit the page.

Index.cshtml

@{
    ViewData["Title"] = "Encryption and Decryption";
    Layout = null;
}

<form method="post" asp-controller="Home" asp-action="EncryptValue">
    Enter value to Encrypt <input type="text" name="inputText" />
    <button type="submit"> Submit</button>
</form>

The below one is a result view. It will display the encrypted and Decrypted values. 

Decrypt.cshtml

@{
    Layout = null;
}

@model Tuple<string, string>

<div>Encrypted Value: <strong>@Model.Item1</strong></div>
<br />
<div>Decrypted Value: <strong>@Model.Item2</strong></div>

The following is an output of the above code. 


I hope it will be helpful for you. Keep coding.



Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example