In this article I will explain with an example, how to use encryption and decryption (Cryptography) in ASP.Net Core MVC.
This article makes use of Symmetric (Same) key AES Algorithm for encryption and decryption process.
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Text;
using System.Security.Cryptography;
 
 
Controller
The Controller consists of following three Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling Encrypt POST operation
Note: For Encryption and Decryption AES encryption algorithm will be used, where a Symmetric (Same) key will be used for encryption and decryption process.
 
This Action method gets called when the Encrypt button is clicked.
Inside this Action method, the original text i.e. clear text is converted into bytes using the GetBytes method of Encoding class and then for the AES algorithm to perform encryption Key and IV is generated using the derived bytes and the symmetric key.
Then, using MemoryStream and CryptoStream the clear text is encrypted and written to byte array and the byte array is converted to Base64String.
Finally, the encrypted text is set in TempData object and then it redirects to the Index Action method.
 
Action method for handling Decrypt POST operation
This method gets called when the Decrypt button is clicked.
Inside this Action method, the encrypted text i.e. cipher text is converted into bytes and then similar to the encryption process a Key and IV is generated using the derived bytes and the symmetric key.
Then, using MemoryStream and CryptoStream the cipher text is decrypted and written to byte array and the byte array is converted to string.
Finally, the decrypted text is set in TempData object and then it redirects to the Index Action method.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Encrypt(string clearText)
    {
        string encryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                TempData["EncryptedText"] = Convert.ToBase64String(ms.ToArray());
            }
        }
 
        return RedirectToAction("Index");
    }
 
    [HttpPost]
    public IActionResult Decrypt(string cipherText)
    {
        string encryptionKey = "MAKV2SPBNI99212";
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                TempData["DecryptedText"] = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
 
        return RedirectToAction("Index");
    }
}
 
 
View
The View consists of an HTML Form which has been created using the ASP.Net Tag Helpers attributes.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of two HTML Input TextBox elements to accept inputs for encryption and decryption, two Input Submit Button elements and two SPAN elements for displaying encrypted and decrypted text.
The Submit Buttons has been set with the POST Action method using the asp-action attribute.
Note: For more details on using Multiple Submit buttons in single View refer my article, Using Multiple Submit Buttons in ASP.Net Core MVC
 
When the Submit Button is clicked, the encrypted and decrypted TempData object is displayed in the respective SPAN element.
Finally, after the TempData object value is read, the Keep function is called which will preserve the value in TempData object.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home">
        <u>Encrypt</u><br /><br />
        <span>Original Text:</span>
        <input type="text" name="clearText"/>
        <br /><br />
        <span>Encrypted Text:</span>
        <span>@TempData["EncryptedText"]</span>
        <br /><br />
        <input type="submit" value="Encrypt" asp-action="Encrypt" />
        <hr />
        <u>Decrypt</u><br /><br />
        <span>Encrypted Text:</span>
        <input type="text" name="cipherText"/>
        <br /><br />
        <span>Decrypted Text:</span>
        <span>@TempData["DecryptedText"]</span>
        <br/><br/>
        <input type="submit" value="Decrypt" asp-action="Decrypt" />
    </form>
    @{
        TempData.Keep("EncryptedText");
    }
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: AES Encryption Decryption (Cryptography) Tutorial with example
 
 
Downloads