Friday, March 28, 2025

OIC - AES encryption and decryption in javascript using CryptoJS

Working...

Use Case

A source application calls an OIC REST service, sending an AES-encrypted request with a cipher key, encrypted message, and IV. OIC needs to decrypt the request, process the data, and encrypt the response before sending it back.

To encrypt a string using the AES algorithm in CBC mode, we need an Encryption Secret, Initialization Vector and Key. Here we will use CryptoJS in javascript.

In the digital era, safeguarding sensitive information is crucial. Encryption serves as a key method to prevent unauthorized access to data. This blog post delves into utilizing CryptoJS, a robust JavaScript library, for encrypting and decrypting data with the AES-256 encryption algorithm.

Steps to follow:

  1. Download the cryptojs file from https://github.com/ihsmarkitosi/CryptoJS-v3.1.2/blob/master/rollups/aes.js
  2. Use the below mentioned encrypt and decrypt code snippet.
  3. First place step1 cryptojs code and then add step2 code. Test it in Online tool to test javascript: https://onecompiler.com/javascript

Encrypt and decrypt code snippet:

function EncryptAESCBC(plaintext, aesKey, aesIV) {

    var key = CryptoJS.enc.Utf8.parse(aesKey);

    var iv = CryptoJS.enc.Utf8.parse(aesIV);

    // Encrypt the plaintext

    var cipherText = CryptoJS.AES.encrypt(plaintext, key, {

        iv: iv,

        mode: CryptoJS.mode.CBC

        //padding: CryptoJS.pad.NoPadding

    });

    var encryptedString = cipherText.toString();

    return encryptedString;

}


function DecryptAESCBC(cipherText, aesKey, aesIV) {

    // IV is a base64 string

    var key = CryptoJS.enc.Utf8.parse(aesKey);

    var iv = CryptoJS.enc.Utf8.parse(aesIV);

    var cipherBytes = CryptoJS.enc.Base64.parse(cipherText);

    var decrypted = CryptoJS.AES.decrypt({ciphertext: cipherBytes}, key, {

        iv: iv,

        mode: CryptoJS.mode.CBC

        //padding: CryptoJS.pad.Pkcs7

    });

    var decryptedString = decrypted.toString(CryptoJS.enc.Utf8);

    return decryptedString;

}

//console.log(DecryptAESCBC(EncryptAESCBC('YWFhYWFhYWFhYWFhYWFhYQ', 'h3Hv332dw8JYJcdx', 'aDNIdjMzMmR3OEpZSmNkeA=='), 'h3Hv332dw8JYJcdx', 'aDNIdjMzMmR3OEpZSmNkeA=='));

Screenshot:


Note: you can also take below updated google cryptojs (rollups /aes.js file)

https://code.google.com/archive/p/crypto-js/downloads

Used in OIC Integrations:

TBD

No comments:

Post a Comment

Featured Post

Types of encryption techniques

There are several types of encryption techniques used to secure data, each with its own use case and strengths: 1. Symmetric Encryption Us...