Saturday 27 November 2021

Encrypt in JavaScript and Decrypt in C# With AES Algorithm in ASP.Net MVC

 In this article we discuss how to Encrypt a razor filed in JavaScript and Decrypt in C# With AES Algorithm in ASP.Net MVC. You know that in web application the security is a major part while we develop a application.


Suppose in a login page, when we post the username and password it shouldn't be in a raw text, the hacker may read the raw text any intercept like (Burp Suite etc.) and read the data. To Secure this we need to encrpt the data in Razor page using AES algorithm using JavaScript and then Decrypt it in C# using same algorithm.

 What is AES Algorithm ?

Advanced Encryption Standard (AES) is a symmetric encryption algorithm.The algorithm was developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen.

The features of AES are as follows −
  • Symmetric key symmetric block cipher
  • 128-bit data, 128/192/256-bit keys
  • Stronger and faster than Triple-DES
  • Provide full specification and design details
  • Software implementable in C and Java
Let's do create a ASP .NET MVC application and in the login page we are going to use the encryption and Decryption method.

   File ➜ New Project ➜ Choose ASP .NET MVC application
   Create a login model Class inside the Models Folder.

public class Login
{
[Required(ErrorMessage = "Enter Username")]
public string Username { get; set; }
[Required(ErrorMessage = "Enter Password")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
view rawLogin.cs hosted with ❤ by GitHub
  Download and add the aes.js in the script folder (The aes.js are shared in Github source code link)
  As we are consider the ASP .NET MVC template then there is already have the HomeController.cs and in Index() we need to add our Login page html code. The complete set of HTML code of index.cshtml is

@model Encrypt_JavaScript_Decrypt_Csharp.Models.Login
@{
ViewBag.Title = "Login";
<script src="../../Scripts/aes.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function CheckData() {
var txtUserName = $('#Username').val();
var txtpassword = $('#Password').val();
if (txtUserName == "") {
alert('Please enter UserName');
return false;
}
else if (txtpassword == "") {
alert('Please enter Password');
return false;
}
else {
var key = CryptoJS.enc.Utf8.parse('8080808080808080');
var iv = CryptoJS.enc.Utf8.parse('8080808080808080');
var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtUserName), key,
{ keySize: 128 / 8, iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
$('#Username').val(encryptedlogin);
var encryptedpassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtpassword), key,
{ keySize: 128 / 8, iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
$('#Password').val(encryptedpassword);
}
}
</script>
}
<h2>
Login
</h2>
@using (Html.BeginForm("Index","Home", FormMethod.Post))
{
if (TempData["notice"] != null)
{
<p>@TempData["notice"]</p>
}
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Userlogin</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Username)
@Html.HiddenFor(model => model.Username)
@Html.ValidationMessageFor(model => model.Username)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Password)
@Html.HiddenFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" onclick="CheckData();" value="LOGIN" /></p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
view rawIndex.cshtml hosted with ❤ by GitHub

Fig-1


Fig-2

Then we need to add the AES encryption method in C# code like below;

public class AESEncryption
{
public static string DecryptStringAES(string cipherText)
{
var keybytes = Encoding.UTF8.GetBytes("8080808080808080");
var iv = Encoding.UTF8.GetBytes("8080808080808080");
var encrypted = Convert.FromBase64String(cipherText);
var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);
return string.Format(decriptedFromJavascript);
}
private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
{
throw new ArgumentNullException("cipherText");
}
if (key == null || key.Length <= 0)
{
throw new ArgumentNullException("key");
}
if (iv == null || iv.Length <= 0)
{
throw new ArgumentNullException("key");
}
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (var rijAlg = new RijndaelManaged())
{
//Settings
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.FeedbackSize = 128;
rijAlg.Key = key;
rijAlg.IV = iv;
// Create a decrytor to perform the stream transform.
var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
try
{
// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
catch
{
plaintext = "keyError";
}
}
return plaintext;
}
private static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
{
throw new ArgumentNullException("plainText");
}
if (key == null || key.Length <= 0)
{
throw new ArgumentNullException("key");
}
if (iv == null || iv.Length <= 0)
{
throw new ArgumentNullException("key");
}
byte[] encrypted;
// Create a RijndaelManaged object
// with the specified key and IV.
using (var rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.FeedbackSize = 128;
rijAlg.Key = key;
rijAlg.IV = iv;
// Create a decrytor to perform the stream transform.
var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
}
And we need to add the Post method where we decrypt the username and password like below;

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Login objUL)
{
if (ModelState.IsValid)
{
var username = AESEncryption.DecryptStringAES(objUL.Username);
var password = AESEncryption.DecryptStringAES(objUL.Password);
if (username == "keyError" && password == "keyError")
{
TempData["notice"] = "Invalid Login";
}
else
{
TempData["notice"] = "login successfully";
}
return View(objUL);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid Login");
return View(objUL);
}
}
When you run the application you can see the output like below;

Fig-3


Fig-4

You can see using below those steps we should do the encryption in razor pages and decryption in C# page.

No comments:

Post a Comment