node.js - Crypto module is not working with latest node 7.10 -
the following code snippet working in node 0.12.18 (replace buffer.from
new buffer
) it's not working latest node version (7.10.0)
can explain me why happening?? 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 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( decipher.final('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')); chunks.push(cipher.final('base64')); var crypted = chunks.join(''); crypted = crypted.concat(itr_str); return crypted; } function randomstring(len, an) { = an&&an.tolowercase(); var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62; for(;i++<len;){ var r = math.random()*(max-min)+min <<0; str += string.fromcharcode(r+=r>9?r<36?55:61:48); } return str; }
node.js v6 introduced backward-incompatible changes crypto
causing this.
i've documented exact reason in this answer, because question related hashing i'm reluctant close question duplicate.
the fix similar, though (you need pass binary
encoding decipher.update()
, otherwise default utf-8
):
chunks.push( decipher.update( buffer.from(_encryption_data, "base64"), 'binary') );
Comments
Post a Comment