一尘不染

使用node.js解密AES256返回错误的最终块长度

node.js

使用此Gist,我能够在Node.js
0.8.7中成功解密AES256。然后,当我升级到Node.js 0.10.24时,现在看到此错误:

TypeError:错误:0606506D:数字信封例程:EVP_DecryptFinal_ex:
Decipheriv.Cipher.final(crypto.js:292:27)的最终块长度错误

这是Gist的解密代码(为方便起见,在此处显示):

var crypto = require('crypto');

var AESCrypt = {};

AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
encryptdata = new Buffer(encryptdata, 'base64').toString('binary');

var decipher = crypto.createDecipheriv('aes-256-cbc', cryptkey, iv),
decoded = decipher.update(encryptdata);

decoded += decipher.final();
return decoded;
}

AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv),
encryptdata = encipher.update(cleardata);

encryptdata += encipher.final();
encode_encryptdata = new Buffer(encryptdata, 'binary').toString('base64');
return encode_encryptdata;
}

var cryptkey = crypto.createHash('sha256').update('Nixnogen').digest(),
iv = 'a2xhcgAAAAAAAAAA',
buf = "Here is some data for the encrypt", // 32 chars
enc = AESCrypt.encrypt(cryptkey, iv, buf);
var dec = AESCrypt.decrypt(cryptkey, iv, enc);

console.warn("encrypt length: ", enc.length);
console.warn("encrypt in Base64:", enc);
console.warn("decrypt all: " + dec);

阅读 233

收藏
2020-07-07

共1个答案

一尘不染

好的,因此将Crypto从0.8更改为0.10时,Crypto方法默认返回Buffer对象,而不是二进制编码的字符串

这意味着以上代码需要指定编码。

这四行:

decoded = decipher.update(encryptdata);
decoded += decipher.final();
encryptdata = encipher.update(cleardata);
encryptdata += encipher.final();

更改为:

decoded = decipher.update(encryptdata, 'binary', 'utf8');
decoded += decipher.final('utf8');
encryptdata = encipher.update(cleardata, 'utf8', 'binary');
encryptdata += encipher.final('binary');

这对我有用,但我愿意接受其他建议。

2020-07-07