Manish Trivedi Manish Trivedi - 3 years ago 62
Node.js Question

Crypto module is not working with latest node 7.10

The following code snippet is working in Node 0.12.18 (replace

new Buffer
) but it's not working with the latest Node version (7.10.0)

Can anybody explain me why this is happening?? Anything is missing in below code.

/* Node.js */
var crypto = require('crypto');

var algorithm = 'aes-256-ctr';

var data = "Dhanet-Kalan-Chittorgarh"
var encryption_key = "VHUz1dxrhsowwEYGqUnPcE4wvAyz7Vmb";

var encryption_data = _encrypt()

console.log('data for encryption :: ' + data);
console.log('encrypted data :: ' + encryption_data);
console.log('decrypted data :: ' + _decrypt(encryption_data));

function _decrypt(_encryption_data){

var decipher, dec, chunks, itr_str;

// remove itr string
itr_str = _encryption_data.substring(_encryption_data.length-24);
_encryption_data = _encryption_data.substring(0, _encryption_data.length-24);

decipher = crypto.createDecipheriv(algorithm, encryption_key, Buffer.from(itr_str, "base64"));
chunks = []
chunks.push( decipher.update( Buffer.from(_encryption_data, "base64").toString("binary")) );
chunks.push('binary') );
dec = chunks.join("");
dec = Buffer.from(dec, "binary").toString("utf-8");

return dec;

function _encrypt(){

//random alpha-numeric string
var itr_str = Buffer.from(randomString(16)).toString('base64') ; // "3V5eo6XrkTtDFMz2QrF3og==";

var cipher = crypto.createCipheriv(algorithm, encryption_key, Buffer.from(itr_str, "base64"));
var chunks = [];
chunks.push(cipher.update( Buffer.from(data), 'utf8', 'base64'));

var crypted = chunks.join('');
crypted = crypted.concat(itr_str);

return crypted;

function randomString(len, an)
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
return str;

Answer Source

Node.js v6 introduced some backward-incompatible changes to crypto which are causing this.

I've documented the exact reason in this answer, but because that question is related to hashing I'm reluctant to close your question as a duplicate.

The fix is similar, though (you need to pass binary as encoding for decipher.update(), otherwise it will default to utf-8):

chunks.push( decipher.update( Buffer.from(_encryption_data, "base64"), 'binary') );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download