Header add

 This article explain how you should Encrypt the value in javascript and pass it into Ajax call and decrypt in MVC Controller using AES Algorithm. In some scenario we need to encrypt the value in the Razor/client page and call the controller using Ajax call, this blog make to you brief details how to we can post this.

Before starting this article you can also visit the previous article Encrypt in JavaScript and Decrypt in C# With AES Algorithm in ASP.Net MVC.

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 create an ASP .NET MVC application and see their how to encrypt and decrypt.

   File ➜ New Project ➜ Choose ASP .NET MVC application
  Create a controller named as HomeController.cs and in Index() is the action code, create a view page of Index and the complete set of HTML code of index.cshtml look like below.

View

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btnSave").click(function () {
           
            var enc1 = 'TestData';

            var key = CryptoJS.enc.Utf8.parse('8080808080808080');
            var iv = CryptoJS.enc.Utf8.parse('8080808080808080');
            var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(enc1), key,
                { keySize: 128 / 8, iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
            var enc = encryptedlogin;
            console.log(enc);
        
          
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetData")',
                data: JSON.stringify({enc: '' + enc + ''}),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function () {
                    alert("Data has been added successfully.");
                },
                error: function () {
                    alert("Error while inserting data");
                }
            });
            return false;
        });
    });
</script>
<h2>Index</h2>
<input type="button" name="Save" value="Save"  id="btnSave"/>


 Code Explanation
  • We added a CDN to use AES algorithm.
  • A HTML button and when it click it should be call to controller page using AJAX Call.
  • You can see we set the test data as var enc1='TestData'
  • var encryptedlogin is hold the encryption data of enc1.
  • Then Finally we declare a variable name as enc and hold the final encrypted data var enc = encryptedlogin;
  • Ajax call made and in controller we create a Action method named as "GetData" that hold the encrypted value. 
Note :  Need to remember pass the data as this format data: JSON.stringify({enc: '' + enc + ''}),


Controller

The Controller code look like below, the GetData() is the JSONResult action method that hold the enc input parameter and decrypt the string using AES algorithm.

 public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetData(string enc)
        {
            var DecryptVal = Utility.DecryptStringAES(enc);
           
            return Json(DecryptVal, JsonRequestBehavior.AllowGet);
        }
    }

AES algorithm class Encryption and Decryption method

public static class Utility
    {
        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;
        }
    }

Final, Run the application and see the ouput.



</> Source Code in Github.com/
Summary
   In this tutorial we discussed Encrypt in javascript and pass it into Ajax call and decrypt in MVC Controller using AES Algorithm. If have any question related to this topic then give your feedback.


Post a Comment

Previous Post Next Post