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

aes

The images are from:

If you want to develop this for ASP.NET Web forms then you can refer to the link Encrypt in JavaScript and Decrypt in C# With AES Algorithm.

What AES algorithm is

Advanced Encryption Standard (AES) is a symmetric encryption algorithm.

The algorithm was developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen.

AES was designed to be efficient in both hardware and software and supports a block length of 128 bits and key lengths of 128, 192 and 256 bits.

Best of all, AES Crypt is completely free open source software.

Since it is open source, several people have contributed to the software and have reviewed the software source code to ensure that it works properly to secure information.

The definition is taken from: http://aesencryption.net/.

Where to use ASE

In today's world we are usually using web based applications where we are prone to various attacks. To prevent attacks from being successful we can use this technique where the data is encrypted at the client side and when the user posts information to the server the data is decrypted at the server side. In MVC 4 we have Html.AntiForgeryToken() for prevention against Cross Site Request Forgery CSRF (XSRF) attacks.
But if we want to encrypt data at the client side then there is nothing available readily for that so for that I am writing this article.

Procedure

  1. Create the solution.
  2. Create the Model.
  3. Add the Controller.
  4. Add a View.
  5. Add an AES JavaScript file.
  6. Add hidden field controls on the forms.
  7. Write the JavaScript for the encryption of field values.
  8. Add AESEncrytDecry code for decrypting.
  9. Finally decrypt on a button click event and get the plain text value from it.

Let's start.

Step 1

Create a new project in ASP.NET MVC 4 with the name MvcEncrypandDecryp. See that in the following snapshot.

MvcEncrypandDecryp

Step 2

After creating a solution I will now add a Model with 4 fields to show the demo.

  1. Username
  2. Password
  3. HDUser
  4. HDpass

For adding the Model just right-click on the Model folder and from the list select Add Class and name it [Userlogin.cs]. See that in the following snapshot.

Add Class

See that in the following snapshot.

master page

After adding the Model you can see a similar view of your project. See that in the following snapshot.

your project

After adding the Model now let's add Properties to it.

  1. Username
  2. Password
  3. HDUser
  4. HDpass

add Properties

After adding the Model let's add the Controller. Before adding it just build the application.

Step 3

For adding the Controller just right-click on the Controller folder and select Add -> Controller.

Controller

After clicking on Controller from the menus list a new dialog pop will pop up as in the following snapshot.

new dialog

Just add the name of the Controller and click on the Add button. I am naming it UserloginController.

After adding the Controller you will see UserloginController in the Controller folder. See that in the following snapshot.

UserloginController

See UserloginController.cs in the following snapshot of after adding the Controller.

UserloginController cs

Now let's modify ActionResult of UserloginController as in the following snapshot.

ActionResult

After changing the UserloginController ActionResult, create 2 methods, one for GET and another for POST, as you can see in the preceding snapshot.

Step 4

Now let's add the View.

To add the View just right-click inside the Action result. See that in the following snapshot.

add View

A new dialog will open asking for the View Name. See that in the following snapshot.

View Name

I will not change the name of the view.

From the View Engine I will select Razor View Engine. And there is a checkbox asking whether to Create a Strongly-typed view; mark it as checked.

In the Model class select the Model Name “ UserLogin ”.

Then in the Scaffold template select the “ Create ” option from the preceding dropdown list.

Now finally click on the Add Button. See that in the following snapshot.

Add Button

After clicking the Add button this kind of View with Code will be generated. See that in the following snapshot.

View with Code

Step 5

After adding the view now let's add the AES JavaScript file to the script folder. If you want download this file then you can download it from link. For adding it just copy and paste the aes.js file into the scripts folder. See that in the following snapshot.

adding just copy paste aes

After adding aes.js to the script folder just reference it on the login page where we are going to encrypt the data.

adding aes

Step 6

Now I am adding 2 hidden fields to the form for storing the encrypted data. See that in the following snapshot.

storing encrypted data

Step 7

After adding it I am adding fields to the forms and now I am writing JavaScript code for encrypting the data on a button submit. See that in the following snapshot.

JavaScript

Now for details of the JavaScript function.

Here in this code I am getting a value from a TextBox (whatever the user enters) in the username and password fields.

  1. var txtUserName = $('#Username').val();  
  2. var txtpassword = $('#Password').val();  
Then encrypting the key and Initialization vector (IV) assigning and it should be of 16 charaters.
  1. var key = CryptoJS.enc.Utf8.parse('8080808080808080');  
  2. var iv = CryptoJS.enc.Utf8.parse('8080808080808080');  
Now encrypting the value for Username and storing the value in hidden fields of HDUser.
  1. var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtUserName), key,  
  2. {
  3.    keySize: 128 / 8,   
  4.    iv: iv,  
  5.    mode: CryptoJS.mode.CBC,  
  6.    padding: CryptoJS.pad.Pkcs7 
  7. });  
  8.   
  9. $('#HDUser').val(encryptedlogin);  
The same now for encrypting the value for Password and storing the value in hidden fields of HDPass.
  1. var encryptedpassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtpassword), key,  
  2.    keySize: 128 / 8,   
  3.    iv: iv,  
  4.    mode: CryptoJS.mode.CBC,  
  5.    padding: CryptoJS.pad.Pkcs7
  6. });  
  7.   
  8. $('#HDpass').val(encryptedpassword);  
After encrypting values I have used an alert to show the Encrypted version of the text.
  1. alert('encrypted login :' + encryptedlogin);  
  2. alert('encrypted password :' + encryptedpassword);  
Now we have done the JavaScript part (client-side part) and are moving to the server side.

Step 8

For that we need to add a class to be the decrypted fields that we have encrypted.

For that I have created a class with the name AESEncrytDecry.cs.

It has the following 2 methods: 
  1. DecryptStringFromBytes
  2. EncryptStringToBytes

And DecryptStringAES is custom-created for decrypting values.

DecryptStringAES

DecryptStringFromBytes Method

  1. private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)  
  2. {  
  3.     // Check arguments.  
  4.     if (cipherText == null || cipherText.Length <= 0)  
  5.     {  
  6.         throw new ArgumentNullException("cipherText");  
  7.     }  
  8.     if (key == null || key.Length <= 0)  
  9.     {  
  10.         throw new ArgumentNullException("key");  
  11.     }  
  12.     if (iv == null || iv.Length <= 0)  
  13.     {  
  14.         throw new ArgumentNullException("key");  
  15.     }  
  16.   
  17.     // Declare the string used to hold  
  18.     // the decrypted text.  
  19.     string plaintext = null;  
  20.   
  21.     // Create an RijndaelManaged object  
  22.     // with the specified key and IV.  
  23.     using (var rijAlg = new RijndaelManaged())  
  24.     {  
  25.         //Settings  
  26.         rijAlg.Mode = CipherMode.CBC;  
  27.         rijAlg.Padding = PaddingMode.PKCS7;  
  28.         rijAlg.FeedbackSize = 128;  
  29.   
  30.         rijAlg.Key = key;  
  31.         rijAlg.IV = iv;  
  32.   
  33.         // Create a decrytor to perform the stream transform.  
  34.         var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);  
  35.   
  36.      try  
  37.         {  
  38.             // Create the streams used for decryption.  
  39.             using (var msDecrypt = new MemoryStream(cipherText))  
  40.             {  
  41. ing (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))  
  42.                 {  
  43.   
  44.                     using (var srDecrypt = new StreamReader(csDecrypt))  
  45.                     {  
  46.                         // Read the decrypted bytes from the decrypting stream  
  47.                         // and place them in a string.  
  48.                         plaintext = srDecrypt.ReadToEnd();  
  49.   
  50.                     }  
  51.   
  52.                 }  
  53.             }  
  54.         }  
  55.         catch  
  56.         {  
  57.             plaintext = "keyError";  
  58.         }  
  59.     }  
  60.   
  61.     return plaintext;  
  62. }  
EncryptStringToBytes Method
  1. private static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)  
  2. {  
  3.     // Check arguments.  
  4.     if (plainText == null || plainText.Length <= 0)  
  5.     {  
  6.         throw new ArgumentNullException("plainText");  
  7.     }  
  8.     if (key == null || key.Length <= 0)  
  9.     {  
  10.         throw new ArgumentNullException("key");  
  11.     }  
  12.     if (iv == null || iv.Length <= 0)  
  13.     {  
  14.         throw new ArgumentNullException("key");  
  15.     }  
  16.     byte[] encrypted;  
  17.     // Create a RijndaelManaged object  
  18.     // with the specified key and IV.  
  19.     using (var rijAlg = new RijndaelManaged())  
  20.     {  
  21.         rijAlg.Mode = CipherMode.CBC;  
  22.         rijAlg.Padding = PaddingMode.PKCS7;  
  23.         rijAlg.FeedbackSize = 128;  
  24.   
  25.         rijAlg.Key = key;  
  26.         rijAlg.IV = iv;  
  27.   
  28.         // Create a decrytor to perform the stream transform.  
  29.         var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);  
  30.   
  31.         // Create the streams used for encryption.  
  32.         using (var msEncrypt = new MemoryStream())  
  33.         {  
  34.           using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))  
  35.             {  
  36.                 using (var swEncrypt = new StreamWriter(csEncrypt))  
  37.                 {  
  38.                     //Write all data to the stream.  
  39.                     swEncrypt.Write(plainText);  
  40.                 }  
  41.                 encrypted = msEncrypt.ToArray();  
  42.             }  
  43.         }  
  44.     }  
  45.   
  46.     // Return the encrypted bytes from the memory stream.  
  47.     return encrypted;  
  48. }  
DecryptStringAES Method
  1. public static string DecryptStringAES(string cipherText)  
  2. {  
  3.     var keybytes = Encoding.UTF8.GetBytes("8080808080808080");  
  4.     var iv = Encoding.UTF8.GetBytes("8080808080808080");  
  5.   
  6.     var encrypted = Convert.FromBase64String(cipherText);  
  7.     var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);  
  8.     return string.Format(decriptedFromJavascript);  
  9. }  
See that in the following snapshot.

snapshot

Now on the button's onclick="return SubmitsEncry();" submit I will call the first JavaScript to Encrypt the data.

And then on the Post of this button I will decrypt the data sent from the client side.
  1. <input type="submit" onclick="SubmitsEncry();" value="Create" />  
Here on the [HttpPost] of the event I am taking values from the hidden fields and then passing them to the class AESEncrytDecry method DecryptStringAES where I will get the decrypted value of it.

Passing the value to this method below.
  1. public static string DecryptStringAES(string cipherText)  
  2. {  
  3.     var keybytes = Encoding.UTF8.GetBytes("8080808080808080");  
  4.     var iv = Encoding.UTF8.GetBytes("8080808080808080");  
  5.   
  6.     var encrypted = Convert.FromBase64String(cipherText);  
  7.     var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);  
  8.     return string.Format(decriptedFromJavascript);  
  9. }
And you will see the that the key and Initialization vector (IV) that we are passing must be similar to what we passed from JavaScript.

Then it will only decrypt the values else give an error.

Step 9

Server-side code for Decryption

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcEncrypandDecryp.Models;  
  7. using ClientsideEncryption;  
  8.   
  9. namespace MvcEncrypandDecryp.Controllers  
  10. {  
  11.     public class UserloginController : Controller  
  12.     {  
  13.         [HttpGet]  
  14.         public ActionResult Login()  
  15.         {  
  16.             return View();  
  17.         }  
  18.   
  19.         [HttpPost]  
  20.         [ValidateAntiForgeryToken]  
  21.         public ActionResult Login(Userlogin objUL )  
  22.         {  
  23.             if (ModelState.IsValid)  
  24.             {  
  25.                 var username = AESEncrytDecry.DecryptStringAES(objUL.HDUser);  
  26.                 var password = AESEncrytDecry.DecryptStringAES(objUL.HDpass);  
  27.   
  28.                 if (username == "keyError" && password == "keyError")  
  29.                 {  
  30.                     TempData["notice"] = "Invalid Login";  
  31.                 }  
  32.                 else  
  33.                 {  
  34.                     TempData["notice"] = "login successfully";  
  35.                 }  
  36.                 return View(objUL);  
  37.             }  
  38.             else  
  39.             {  
  40.                 ModelState.AddModelError(string.Empty, "Invalid Login");  
  41.                 return View(objUL);  
  42.             }  
  43.         }  
  44.   
  45.     }  
  46. }  
Now just run your application and check it.

The login page view.

See that in the following snapshot.

login

Username Encrypted value.

See that in the following snapshot.

below snapshot

Password Encrypted value.

See that in the following snapshot.

Password Encrypted

The value of the client side is posted to the server side as shown here in the following snapshot.

server side

After decryption the value is shown in the following snapshot.

decryption value

To protect sensitive data, the best practice is to use HTTPS instead of HTTP.

The HTTPS protocol will automatically encrypt sensitive information that is posted from the client to the server, so nobody can use network sniffers to intercept and read the information.

Finally we have completed the encryption in JavaScript and decryption in C# with the AES algorithm in ASP.Net in MVC 4.


Similar Articles