NodeJS How To Encrypt (AES Algorithm) Data Using Crypto-js, Or Crypto Package Encoded In UTF8 Using Custom Keysize, Iv, Mode And Padding
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.
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
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error