Search This Blog

Thursday, October 8, 2015

Encrypt in JavaScript and Decrypt in C# With 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.
Please find the reference URL :
http://www.c-sharpcorner.com/UploadFile/4d9083/encrypt-in-javascript-and-decrypt-in-C-Sharp-with-aes-algorithm/


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.
  1. <script type="text/javascript">  
  2.   
  3.         function SubmitsEncry() {  
  4.   
  5.             debugger;  
  6.             var txtUserName = document.getElementById("<%=txtUserName.ClientID %>").value.trim();  
  7.             var txtpassword = document.getElementById("<%=txtpassword.ClientID %>").value.trim();  
  8.   
  9.             if (txtUserName == "") {  
  10.                 alert('Please enter UserName');  
  11.                 return false;  
  12.             }  
  13.             else if (txtpassword == "") {  
  14.                 alert('Please enter Password');  
  15.                 return false;  
  16.             }  
  17.             else {  
  18.                 var key = CryptoJS.enc.Utf8.parse('8080808080808080');  
  19.                 var iv = CryptoJS.enc.Utf8.parse('8080808080808080');  
  20.   
  21.                 var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtUserName), key,  
  22.                 {  
  23.                     keySize: 128 / 8,  
  24.                     iv: iv,  
  25.                     mode: CryptoJS.mode.CBC,  
  26.                     padding: CryptoJS.pad.Pkcs7  
  27.                 });  
  28.   
  29.                 document.getElementById("<%=HDusername.ClientID %>").value = encryptedlogin;  
  30.   
  31.                 var encryptedpassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtpassword), key,  
  32.                 {  
  33.                     keySize: 128 / 8,  
  34.                     iv: iv,  
  35.                     mode: CryptoJS.mode.CBC,  
  36.                     padding: CryptoJS.pad.Pkcs7  
  37.                 });  
  38.   
  39.                 document.getElementById("<%=HDPassword.ClientID %>").value = encryptedpassword;  
  40.   
  41.                 alert('encrypted login :' + encryptedlogin);  
  42.                 alert('encrypted password :' + encryptedpassword);  
  43.             }  
  44.         }  
  45.     </script>  
Here in this code I am getting the value from the TextBox that the user entered into the username and password fields.
  1. var txtUserName = document.getElementById("<%=txtUserName.ClientID %>").value;  
  2. var txtpassword = document.getElementById("<%=txtpassword.ClientID %>").value;  
Then encrypting a 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 the hidden fields of HDusername.
  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. });   
    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.
  1. var encryptedpassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtpassword), key,  
  2. {  
  3. keySize: 128 / 8,  
  4. iv: iv,  
  5. mode: CryptoJS.mode.CBC,  
  6. padding: CryptoJS.pad.Pkcs7  
  7. });  
  8.   
  9. document.getElementById("<%=HDPassword.ClientID %>").value = encryptedpassword;  
After Encrypting values I used an alert to show an Encrypted version of text.
  1. alert('encrypted login :' + encryptedlogin);  
  2. 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:
  1. DecryptStringFromBytes
  2. EncryptStringToBytes
And DecryptStringAES is custom-created for decrypting the values.



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.             using (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.    // Return the encrypted bytes from the memory stream.  
  46.    return encrypted;  
  47. }  
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. }  
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.
  1. <asp:Button ID="btnlogin" OnClientClick="return SubmitsEncry();" runat="server" Text="Sign In"  
  2. 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:
  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 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
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. namespace ClientsideEncryption  
  9. {  
  10.     public partial class login : System.Web.UI.Page  
  11.     {  
  12.         protected void Page_Load(object sender, EventArgs e)  
  13.         {  
  14.   
  15.         }  
  16.   
  17.         protected void btnlogin_Click(object sender, EventArgs e)  
  18.         {  
  19.             if (Page.IsValid)  
  20.             {  
  21.                 if (string.IsNullOrEmpty(HDusername.Value))  
  22.                 {  
  23. ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Enter Username');"true);  
  24.                 }  
  25.                 else if (string.IsNullOrEmpty(HDPassword.Value))  
  26.                 {  
  27.  ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Enter Password !');"true);  
  28.                 }  
  29.                 else  
  30.                 {  
  31.                     var username = AESEncrytDecry.DecryptStringAES(HDusername.Value);  
  32.                     var password = AESEncrytDecry.DecryptStringAES(HDPassword.Value);  
  33.                 }  
  34.   
  35.                  if (username == "keyError" && password == "keyError")  
  36.                     {  
  37.   
  38.   ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('Not vaild login');"true);  
  39.   
  40.                     }  
  41.                     else  
  42.                     {  
  43.   
  44.  ScriptManager.RegisterStartupScript(thisthis.GetType(), "alert""alert('login successfully');"true);  
  45.   
  46.                     }  
  47.   
  48.   
  49.             }  
  50.         }  
  51.     }  
  52. }  



Finally we have some ways to secure client-side fields using the AES algorithm