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.
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 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', Buffer.from(key), Buffer.from(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