0

The following code snippet is working in Node 0.12.18 (replace Buffer.from to 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( 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&&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;
}
4

1 回答 1

1

cryptoNode.js v6 引入了一些导致这种情况的向后不兼容的更改。

我已经在这个答案中记录了确切的原因,但是因为这个问题与散列有关,所以我不愿意将你的问题作为重复来关闭。

不过,修复是类似的(您需要binary作为编码传递decipher.update(),否则它将默认为utf-8):

chunks.push( decipher.update( Buffer.from(_encryption_data, "base64"), 'binary') );
于 2017-07-25T14:11:00.137 回答