简体   繁体   中英

Node.JS Crypto Cipher/Decipher not working

Here is the code:

    var kk = JSON.stringify(object);
    console.log(kk);
    var kk1 = encrypt(kk);
    console.log(kk1)
    var kk2 = decrypt(kk1);
    console.log(kk2)
    this.write(encrypt(kk))

Functions:

var encrypt = function (data) {
    var cipher = crypto.createCipher('aes-256-ecb', password)
    cipher.update(data, 'utf8')
    return cipher.final('hex')
}
var decrypt = function (data) {
    var cipher = crypto.createDecipher('aes-256-ecb', password)
    cipher.update(data, 'hex')
    return cipher.final('utf8')
}

console message:

{"action":"ping","ping":30989}
4613a3a8719c921eed61e19b7480de9c
,"ping":30989}

Why decrypting doesn't result into initial string?

.update() returns partially ciphered/deciphered content and you're immediately discarding that data. You're also missing the output encoding for .update() that matches what you're using in .final() . Try this:

function encrypt(data) {
  var cipher = crypto.createCipher('aes-256-ecb', password);
  return cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
}

function decrypt(data) {
  var cipher = crypto.createDecipher('aes-256-ecb', password);
  return cipher.update(data, 'hex', 'utf8') + cipher.final('utf8');
}

Given that .update() and .final() are mentioned to be legacy methods in the crypto module , I thought I'd provide a second way. Cipher objects are streams , so you can do:

function encrypt(data) {
    var text = JSON.stringify(data);
    var textBuffer = new Buffer(text, 'utf8');
    var cipher = crypto.createCipher('aes-256-ecb', password);
    cipher.write(textBuffer);
    cipher.end();
    return cipher.read().toString('hex');
}

function decrypt(hexString) {
    var hexBuffer = new Buffer(hexString, 'hex');
    var decipher = crypto.createDecipher('aes-256-ecb', password);
    decipher.write(hexBuffer);
    decipher.end();
    var data = decipher.read().toString('utf8');
    return JSON.parse(data);
}

I added JSON.stringify and parse to handle numbers/objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM