使用 node.js 解密 AES256 返回错误的最终块长度 [英] Decrypting AES256 with node.js returns wrong final block length

查看:29
本文介绍了使用 node.js 解密 AES256 返回错误的最终块长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using this Gist I was able to successfully decrypt AES256 in Node.js 0.8.7. Then when I upgraded to Node.js 0.10.24, I now see this error:

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

TypeError: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Decipheriv.Cipher.final (crypto.js:292:27)

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

Here is the decrypt code from the Gist (shown here for convenience):

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);

推荐答案

好的,所以在从 0.8 到 0.10 的切换中对 Crypto 进行了更改 加密方法默认返回 Buffer 对象,而不是二进制编码的字符串

Ok, so there was a change to Crypto in the switch from 0.8 to 0.10 Crypto methods return Buffer objects by default, rather than binary-encoded strings

这意味着上面的代码需要指定编码.

This means the above code needs to specify encodings.

这四行:

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');

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

This worked for me, but I am open to other suggestions.

这篇关于使用 node.js 解密 AES256 返回错误的最终块长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆