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
- Create the solution.
- Create the Model.
- Add the Controller.
- Add a View.
- Add an AES JavaScript file.
- Add hidden field controls on the forms.
- Write the JavaScript for the encryption of field values.
- Add AESEncrytDecry code for decrypting.
- 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.
Step 2
After creating a solution I will now add a Model with 4 fields to show the demo.
- Username
- Password
- HDUser
- 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.
See that in the following snapshot.
After adding the Model you can see a similar view of your project. See that in the following snapshot.
After adding the Model now let's add Properties to it.
- Username
- Password
- HDUser
- HDpass
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.
After clicking on Controller from the menus list a new dialog pop will pop up as in the following snapshot.
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.
See UserloginController.cs in the following snapshot of after adding the Controller.
Now let's modify ActionResult of UserloginController as in the following snapshot.
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.
A new dialog will open asking for the View Name. See that in the following snapshot.
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.
After clicking the Add button this kind of View with Code will be generated. See that in the following snapshot.
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.
After adding aes.js to the script folder just reference it on the login page where we are going to encrypt the data.
Step 6
Now I am adding 2 hidden fields to the form for storing the encrypted data. See that in the following snapshot.
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.
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.
- var txtUserName = $('#Username').val();
- var txtpassword = $('#Password').val();
Then encrypting the key and Initialization vector (IV) assigning and it should be of 16 charaters.
- var key = CryptoJS.enc.Utf8.parse('8080808080808080');
- var iv = CryptoJS.enc.Utf8.parse('8080808080808080');
Now encrypting the value for Username and storing the value in hidden fields of HDUser.
- var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtUserName), key,
- {
- keySize: 128 / 8,
- iv: iv,
- mode: CryptoJS.mode.CBC,
- padding: CryptoJS.pad.Pkcs7
- });
-
- $('#HDUser').val(encryptedlogin);
The same now for encrypting the value for Password and storing the value in hidden fields of HDPass.
- var encryptedpassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtpassword), key,
- {
- keySize: 128 / 8,
- iv: iv,
- mode: CryptoJS.mode.CBC,
- padding: CryptoJS.pad.Pkcs7
- });
-
- $('#HDpass').val(encryptedpassword);
After encrypting values I have used an alert to show the Encrypted version of the text.
- alert('encrypted login :' + encryptedlogin);
- 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:
- DecryptStringFromBytes
- EncryptStringToBytes
And DecryptStringAES is custom-created for decrypting values.
DecryptStringFromBytes Method
- private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
- {
-
- 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");
- }
-
-
-
- string plaintext = null;
-
-
-
- using (var rijAlg = new RijndaelManaged())
- {
-
- rijAlg.Mode = CipherMode.CBC;
- rijAlg.Padding = PaddingMode.PKCS7;
- rijAlg.FeedbackSize = 128;
-
- rijAlg.Key = key;
- rijAlg.IV = iv;
-
-
- var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
-
- try
- {
-
- using (var msDecrypt = new MemoryStream(cipherText))
- {
- ing (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
- {
-
- using (var srDecrypt = new StreamReader(csDecrypt))
- {
-
-
- plaintext = srDecrypt.ReadToEnd();
-
- }
-
- }
- }
- }
- catch
- {
- plaintext = "keyError";
- }
- }
-
- return plaintext;
- }
EncryptStringToBytes Method
- private static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
- {
-
- 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;
-
-
- using (var rijAlg = new RijndaelManaged())
- {
- rijAlg.Mode = CipherMode.CBC;
- rijAlg.Padding = PaddingMode.PKCS7;
- rijAlg.FeedbackSize = 128;
-
- rijAlg.Key = key;
- rijAlg.IV = iv;
-
-
- var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
-
-
- using (var msEncrypt = new MemoryStream())
- {
- using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
- {
- using (var swEncrypt = new StreamWriter(csEncrypt))
- {
-
- swEncrypt.Write(plainText);
- }
- encrypted = msEncrypt.ToArray();
- }
- }
- }
-
-
- return encrypted;
- }
DecryptStringAES Method
- 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);
- }
See that in the following 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.
- <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.
- 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);
- }
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcEncrypandDecryp.Models;
- using ClientsideEncryption;
-
- namespace MvcEncrypandDecryp.Controllers
- {
- public class UserloginController : Controller
- {
- [HttpGet]
- public ActionResult Login()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Login(Userlogin objUL )
- {
- if (ModelState.IsValid)
- {
- var username = AESEncrytDecry.DecryptStringAES(objUL.HDUser);
- var password = AESEncrytDecry.DecryptStringAES(objUL.HDpass);
-
- 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);
- }
- }
-
- }
- }
Now just run your application and check it.
The login page view.
See that in the following snapshot.
Username Encrypted value.
See that in the following snapshot.
Password Encrypted value.
See that in the following snapshot.
The value of the client side is posted to the server side as shown here in the following snapshot.
After decryption the value is shown in the following snapshot.
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.