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 System.Security.Cryptography class and AES algorithm for encryption and decryption in ASP.Net MVC.
Controllers
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation – Form 1
This Action method gets called when Encrypt Button is clicked or when the Form is submitted.
Inside this Action method, the value of the TextBox is encrypted using Encrypt method and set into a TempData object.
Encrypt
Inside the Encrypt method, first the secret key is defined for the encryption and converted into a BYTE array using GetBytes method of the Encoding class.
And the plain text captured from the TextBox is also converted into a BYTE array.
Note: For Encryption and Decryption, AES encryption algorithm will be used, where a Symmetric (Same) key will be used for encryption and decryption process.
Then, an object of AES class (AES Symmetric key algorithm) is created for performing encryption and its necessary properties are set.
Key � For defining the EncryptionKey.
Mode � It defines the mode of the operation. Here it is CipherMode.ECB (Electronic Codebook).
Padding � It specifies padding mode.
After that, an object of ICryptoTransform is created and CreateEncryptor method of AES class (AES Symmetric key algorithm) is called.
Then, using TransformFinalBlock method of ICryptoTransform class object the plain text is encrypted and stored as BYTE array.
Finally, the BYTE array is converted into a BASE64 string and string value is returned.
Action method for handling POST operation – Form 2
This Action method gets called when Decrypt Button is clicked or when the Form is submitted.
Inside this Action method, the encrypted text is decrypted using Decrypt method and set into a TempData object.
Decrypt
Inside the Decrypt method, first the secret key is defined for the decryption and converted into a BYTE array using GetBytes method of the Encoding class.
And the decrypted text text is also converted into a BYTE array.
Note: For Encryption and Decryption, AES encryption algorithm will be used, where a Symmetric (Same) key will be used for encryption and decryption process.
Then, an object of AES class (AES Symmetric key algorithm) is created for performing encryption and its necessary properties are set.
Key � For defining the EncryptionKey.
Mode � It defines the mode of the operation. Here it is CipherMode.ECB (Electronic Codebook).
Padding � It specifies padding mode.
After that, an object of ICryptoTransform is created and CreateEncryptor method of AES class (AES Symmetric key algorithm) is called.
Then, using TransformFinalBlock method of ICryptoTransform class object the plain text is encrypted and stored as BYTE array.
Finally, the BYTE array is converted into a BASE64 string and string value is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Encryption(string plainText)
{
TempData["EncryptedValue"] = this.Encrypt(plainText);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Decryption(string encryptedValue)
{
TempData["DecryptedValue"] = this.Decrypt(encryptedValue);
return RedirectToAction("Index");
}
private string Encrypt(string plainText)
{
//Secret Key.
string secretKey = "$ASPcAwSNIgcPPEoTSa0ODw#";
//Secret Bytes.
byte[] secretBytes = Encoding.UTF8.GetBytes(secretKey);
//Plain Text Bytes.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
//Encrypt with AES Alogorithm using Secret Key.
using (Aes aes = Aes.Create())
{
aes.Key = secretBytes;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] encryptedBytes = null;
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
encryptedBytes = encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
}
return Convert.ToBase64String(encryptedBytes);
}
}
private string Decrypt(string encryptedText)
{
//Secret Key.
string EncryptsecretKey = "$ASPcAwSNIgcPPEoTSa0ODw#";
//Secret Bytes.
byteEncrypt[] secretBytes = Encoding.UTF8.GetBytes(secretKey);
//Encrypted Bytes.
byteEncrypt[] encryptedBytes = Convert.FromBase64String(encryptedText);
//Decrypt with AES Alogorithm using Secret Key.
using (Aes aes = Aes.Create())
{
aes.Key = secretBytes;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] decryptedBytes = null;
using (ICryptoTransform decryptor = aes.CreateDecryptor())
{
decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
}
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
View
HTML Markup
The View consists of two HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action.
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.
Encryption Form
The Form consists of a TextBox created using Html.TextBox method and a Submit Button.
It also consists of an HTML SPAN element which is used to display the encrypted value.
Decryption Form
This Form consists of a HiddenField created using Html.Hidden method which is used to store the encrypted value.
It also consists of a Submit Button which when clicked the decrypted value is displayed suing HTML SPAN element.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Encryption", "Home", FormMethod.Post))
{
<span>Plain Text:</span>
@Html.TextBox("PlainText")
<input type="submit" value="Encrypt" />
<br />
<span>Encrypted Text: @TempData["EncryptedValue"]</span>
}
<hr />
@using (Html.BeginForm("Decryption", "Home", FormMethod.Post))
{
@Html.Hidden("EncryptedValue", TempData["EncryptedValue"])
<input type="submit" value="Decrypt" />
<br />
<br />
<span>Decrypted Value: @TempData["DecryptedValue"]</span>
}
</body>
</html>
Screenshot
Demo
Downloads