Ad

NodeJS How To Encrypt (AES Algorithm) Data Using Crypto-js, Or Crypto Package Encoded In UTF8 Using Custom Keysize, Iv, Mode And Padding

- 1 answer

I am working with an API that require me to encrypt data before sending it with custom parameters and I am unable to get a good response from the server.

I want to be sure this code is correct for this operation because my response from the server says it's unable to process my request. "Error Processing Request"

Below is a the sample code I got from the Postman collection.

CryptoJS = require('crypto-js');



AES_ENCRYPT = function(){
  var key = "1234567";
  var iv  = "7654321";
  key = CryptoJS.enc.Utf8.parse(key);
  iv = CryptoJS.enc.Utf8.parse(iv);
  const encryptData = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(rawData), 
  key,
    {
         keySize: 128 / 8,
         iv: iv,
         mode: CryptoJS.mode.CBC,
         padding: CryptoJS.pad.Pkcs7
    });
 return encryptData;
}

From my experience when encryption is done we get a string in return but in this case I am not getting a string and I have tried encryptData.toString() on the return value but no luck.

I want to know if I can do this same operation using another node package to get the right result or do this the right way using same crypto-js package.

Ad

Answer

You should use built-in module, crypto as it is easier to use and have more resources online.

var crypto = require('crypto');

var iv = 'some 16 byte iv';
var key = 'some 16 byte long key';
var plainText = 'some plain text';
var algo = 'aes-128-cbc'; // we are using 128 bit here because of the 16 byte key. use 256 is the key is 32 byte.

var cipher = crypto.createCipheriv('aes-128-cbc', new Buffer(key), new Buffer(iv));
var encrypted = cipher.update(plainText, 'utf-8', 'base64'); // `base64` here represents output encoding
encrypted += cipher.final('base64');

console.log('encrypted'); //returns encrypted data in base64 encoding
Ad
source: stackoverflow.com
Ad