Node.JS Crypto Cipher/Decipher无法正常工作

Nic*_*ing 1 javascript cryptography node.js

这是代码:

    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))
Run Code Online (Sandbox Code Playgroud)

功能:

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')
}
Run Code Online (Sandbox Code Playgroud)

控制台消息:

{"action":"ping","ping":30989}
4613a3a8719c921eed61e19b7480de9c
,"ping":30989}
Run Code Online (Sandbox Code Playgroud)

为什么解密不会导致初始字符串?

msc*_*dex 11

.update()返回部分加密/解密的内容,您立即丢弃该数据.您还缺少.update()与您正在使用的输出编码相匹配的输出编码.final().试试这个:

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');
}
Run Code Online (Sandbox Code Playgroud)