In this article I will explain with an example, how to use encryption and decryption (Cryptography) in ASP.Net 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 two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation
This Action method handles the call made from the POST function from the View when the Submit Button is clicked.
Note: For more details on calling multiple Action Methods using single Form refer my article, Calling multiple Action methods using Single Form in ASP.Net MVC.
 
Inside this Action method, the value of the clicked Submit button is fetched using its Name from the Request.Form collection and following method i.e. Encrypt or Decrypt is called.
Note: For Encryption and Decryption AES encryption algorithm will be used, where a Symmetric (Same) key will be used for encryption and decryption process.
 
Encrypt
This method gets called when the Encrypt button is clicked.
Inside the Encrypt 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 view is returned.
 
Decrypt
This method gets called when the Decrypt button is clicked.
Inside the Decrypt 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 view is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(string submit, string clearText, string cipherText)
    {
        switch (submit)
        {
            case "Encrypt":
                TempData["EncryptedText"] = this.Encrypt(clearText);
                break;
            case "Decrypt":
                TempData["DecryptedText"] = this.Decrypt(cipherText);
                break;
        }
 
        return View();
    }
 
    private string 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();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
 
        return clearText;
    }
 
    private string 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();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
 
        return cipherText;
    }
}
 
 
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – 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.
This Action method handles the call made from the POST function from the View when the Submit Button is clicked.
Note: For more details on using Multiple Submit buttons in single Form refer my article, Using Multiple Submit buttons in Single Form in ASP.Net 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.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <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" name="submit" value="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" name="submit" value="Decrypt" />
    }
    @{
        TempData.Keep("EncryptedText");
    }
</body>
</html>
 
 
Screenshot
ASP.Net MVC: AES Encryption Decryption (Cryptography) Tutorial with example
 
 
Downloads