AES Algorithm
The Advanced Encryption Standard (AES) is a symmetric encryption algorithm.
The algorithm was developed by the 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 a 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 web based applications are often used where we are vulnerable to various attacks. To prevent them we can use the technique of getting data encrypted at the client side and when the user posts the information to the server the data will be decrypted at the server side.
Procedure
- Creating solution.
- Adding AES JavaScript file.
- Adding controls on Forms.
- Writing JavaScript for Encryption of fields value.
- Adding AESEncrytDecry code for decrypting.
- Finally decrypting on button click event and getting plain text value from it.
Let's start.
Step 1
Create a new ASP.Net solution project with the name ClientsideEncryption as in the following snapshot.
Then I have added a page with the name login.aspx in which we will do encryption and decryption as in the following snapshot.
Step 2
After adding login page I will add a reference of AES JavaScript to the login page for encryption.
If you want tp download this file you can download it from the following link:
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js
And after downloading just add this to your script folder.
See in the following snapshot.
After adding aes.js to the script folder just reference on the login page where we will encrypt the data.
Step 3
Now I am adding fields to the form.
I have added 2 TextBoxes and 2 hidden fields and a button on page.
Step 4
After adding that I am adding fields to the forms. Now to write JavaScript code for encrypting data on the button submit.
<script type="text/javascript">
function SubmitsEncry() {
debugger;
var txtUserName = document.getElementById("<%=txtUserName.ClientID %>").value.trim();
var txtpassword = document.getElementById("<%=txtpassword.ClientID %>").value.trim();
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
});
document.getElementById("<%=HDusername.ClientID %>").value = 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
});
document.getElementById("<%=HDPassword.ClientID %>").value = encryptedpassword;
alert('encrypted login :' + encryptedlogin);
alert('encrypted password :' + encryptedpassword);
}
}
</script>
Here in this code I am getting the value from the TextBox that the user entered into the username and password fields.
var txtUserName = document.getElementById("<%=txtUserName.ClientID %>").value;
var txtpassword = document.getElementById("<%=txtpassword.ClientID %>").value;
Then encrypting a 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 the hidden fields of HDusername.
var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtUserName), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
document.getElementById("<%=HDusername.ClientID %>").value = encryptedlogin;
Now do the same for encrypting the value for Password and storing the value in hidden fields of HDPassword.
var encryptedpassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtpassword), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
document.getElementById("<%=HDPassword.ClientID %>").value = encryptedpassword;
After Encrypting values I used an alert to show an Encrypted version of text.
alert('encrypted login :' + encryptedlogin);
alert('encrypted password :' + encryptedpassword);
Now we have completed the JavaScript part (the client side part) and are now moving to the server side.
Step 5
For that we need to add a Class that will 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 the values.
DecryptStringFromBytes Method
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;
}
EncryptStringToBytes Method
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;
}
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);
}
Now on the button's OnClientClick="return SubmitsEncry();" submit I will call first JavaScript to encrypt the data.
And then OnClick="btnlogin_Click" I will decrypt data.
<asp:Button ID="btnlogin" OnClientClick="return SubmitsEncry();" runat="server" Text="Sign In"
OnClick="btnlogin_Click" />
Here on the Button click event I am taking values from hidden fields and then passing them to the class AESEncrytDecry and the method DecryptStringAES where I will get the decrypted value of it .
The value is passed to this method as in the following:
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 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 values else gives an error.
Step 6
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ClientsideEncryption
{
public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnlogin_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (string.IsNullOrEmpty(HDusername.Value))
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Enter Username');", true);
}
else if (string.IsNullOrEmpty(HDPassword.Value))
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Enter Password !');", true);
}
else
{
var username = AESEncrytDecry.DecryptStringAES(HDusername.Value);
var password = AESEncrytDecry.DecryptStringAES(HDPassword.Value);
}
if (username == "keyError" && password == "keyError")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Not vaild login');", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('login successfully');", true);
}
}
}
}
}
Now just run the application and check the values.
The page view.
Username encrypted value.
Password encrypted value.
The value of the client side is posted to the server side. The following is the snapshot.
After decryption the value is show as in the following snapshot.
Finally we have some ways to secure client-side fields using the AES algorithm.