AES Encryption in C# and decryption in CryptoJS

17,885

It is working now after getting some reference from Google CryptoJS group (https://groups.google.com/forum/#!msg/crypto-js/ysgzr2Wxt_k/_Wh8l_1rhQAJ).

Here is encryption code in C#.NET.

public class ClsCrypto
{
    private RijndaelManaged myRijndael = new RijndaelManaged();
    private int iterations;
    private byte [] salt;

    public ClsCrypto(string strPassword)
    {
        myRijndael.BlockSize = 128;
        myRijndael.KeySize = 128;
        myRijndael.IV = HexStringToByteArray("e84ad660c4721ae0e84ad660c4721ae0");

        myRijndael.Padding = PaddingMode.PKCS7;
        myRijndael.Mode = CipherMode.CBC;
        iterations = 1000;
        salt = System.Text.Encoding.UTF8.GetBytes("insight123resultxyz");
        myRijndael.Key = GenerateKey(strPassword);
    }

    public string Encrypt(string strPlainText)
    {
        byte [] strText = new System.Text.UTF8Encoding().GetBytes(strPlainText);
        ICryptoTransform transform = myRijndael.CreateEncryptor();
        byte [] cipherText = transform.TransformFinalBlock(strText, 0, strText.Length);

        return Convert.ToBase64String(cipherText);
    }

    public string Decrypt(string encryptedText)
    {
       byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
       var decryptor = myRijndael.CreateDecryptor(myRijndael.Key, myRijndael.IV);
       byte[] originalBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);

       return Encoding.UTF8.GetString(originalBytes);
    }

    public static byte [] HexStringToByteArray(string strHex)
    {
        dynamic r = new byte[strHex.Length / 2];
        for (int i = 0; i <= strHex.Length - 1; i += 2)
        {
            r[i/2] = Convert.ToByte(Convert.ToInt32(strHex.Substring(i, 2), 16));
        }
        return r;
    }

    private byte[] GenerateKey(string strPassword)
    {
        Rfc2898DeriveBytes rfc2898 = new          Rfc2898DeriveBytes(System.Text.Encoding.UTF8.GetBytes(strPassword), salt, iterations);

        return rfc2898.GetBytes(128 / 8);
    }
}

Following is decryption code in Java script.

<head runat="server">
        <script src="rollups/aes.js" type="text/javascript"></script>
        <script src="rollups/sha256.js" type="text/javascript"></script>
        <script src="rollups/pbkdf2.js" type="text/javascript"></script>
        <script type="text/javascript">
          function DecryptData() {
            var encryptData = document.getElementById('TextEncrypted').value;
            var decryptElement = document.getElementById('TextDecrypt');
    
            try {
                //Creating the Vector Key
                var iv = CryptoJS.enc.Hex.parse('e84ad660c4721ae0e84ad660c4721ae0');
                //Encoding the Password in from UTF8 to byte array
                var Pass = CryptoJS.enc.Utf8.parse('insightresult');
                //Encoding the Salt in from UTF8 to byte array
                var Salt = CryptoJS.enc.Utf8.parse("insight123resultxyz");
                //Creating the key in PBKDF2 format to be used during the decryption
                var key128Bits1000Iterations = CryptoJS.PBKDF2(Pass.toString(CryptoJS.enc.Utf8), Salt, { keySize: 128 / 32, iterations: 1000 });
                //Enclosing the test to be decrypted in a CipherParams object as supported by the CryptoJS libarary
                var cipherParams = CryptoJS.lib.CipherParams.create({
                    ciphertext: CryptoJS.enc.Base64.parse(encryptData)
                });
    
                //Decrypting the string contained in cipherParams using the PBKDF2 key
                var decrypted = CryptoJS.AES.decrypt(cipherParams, key128Bits1000Iterations, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7 });
                decryptElement.value = decrypted.toString(CryptoJS.enc.Utf8);
            }
            //Malformed UTF Data due to incorrect password
            catch (err) {
                return "";
            }
        }
    </script>
</head>
Share:
17,885
Pabitra Dash
Author by

Pabitra Dash

More than 20 years experience in IT industry at different roles and responsibility in medical imaging (MR, PET and Ultrasound) product development, cross platform educatioal software developemnt, web based ATM/POS transaction monitoring solutions, payment and security system for computer gaming club, quote addon module for MS dynamic CRM, socket server and MS outlook add-in development. Specialties:Medical Image Processing (2D/3D), Web services, Cross platform development in Windows and Macintosh, Onsite coordinator, project management, Design patterns, business model using Rational XDE for .NET, Socket Programming, Game application development using WPF. C,C++,VC++/MFC, C#.NET, Silverlight, WCF, Entity Framework, MVC 5, Web services and Java script Ratioal XDE for .NET, Visio You can reach me at [email protected]

Updated on July 13, 2022

Comments

  • Pabitra Dash
    Pabitra Dash almost 2 years

    I would like to do AES Encryption in C# and decryption in CryptoJS.

  • Jarekczek
    Jarekczek about 8 years
    This is my code for js encoding/decoding, supplementing your suggestion: var cfg = { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7 }; var encrypted = CryptoJS.AES.encrypt("MMMessageąćęł", key, cfg); var sEncrypted = CryptoJS.enc.Base64.stringify(encrypted.ciphertext); var decrypted2 = CryptoJS.AES.decrypt(sEncrypted, key, cfg);
  • Jarekczek
    Jarekczek about 8 years
    Note that IV should be initiated randomly for every encryption run. You cannot you the same IV twice, for security reasons. en.wikipedia.org/wiki/…
  • Calin Pirtea
    Calin Pirtea almost 4 years
    Thank you, @user2025187. This code was super useful.