我创建了通用的crypt和decrypt功能,当我提供任意字符串时它工作正常但是当我尝试传入sha256
哈希字符串时,crypto会抛出错误 - error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
这是代码 -
let crypto = require('crypto');
const secret = new Buffer('1234567890abcdef71234567890abcdef1234567890abcdef1234567890abcdef', 'hex');
const iv = new Buffer('1234567890abcdef1234567890abcdef', 'hex');
const config = {
secret: secret,
iv: iv
};
function encrypt(data, sec, siv) {
let dataBuffer = ((data instanceof Buffer)?data:Buffer.from(data));
let cipher = crypto.createCipheriv('aes-256-cbc', sec, siv);
let crypt = cipher.update(dataBuffer);
crypt += cipher.final('hex');
return Buffer.from(crypt, 'hex');
}
function decrypt(data, sec, siv) {
let dataBuffer = ((data instanceof Buffer)?data:Buffer.from(data));
let decipher = crypto.createDecipheriv('aes-256-cbc', sec, siv);
let decrypt = decipher.update(dataBuffer);
decrypt += decipher.final();
return Buffer.from(decrypt);
}
function main() {
let test = 'asdfqwerty';
let secretBytes = crypto.randomBytes(32);
let secretHash = Buffer.from(crypto.createHmac('sha256', config.secret).update(secretBytes).digest('hex'));
console.log('\nTesting test string\n===================');
console.log(test);
a = encrypt(test, config.secret, config.iv);
console.log(decrypt(a, config.secret, config.iv).toString());
console.log('\nTesting test string\n===================');
console.log(secretHash);
a = encrypt(secretHash, config.secret, config.iv);
console.log(decrypt(a, config.secret, config.iv).toString());
}
try {
main();
} catch (e) {
console.log(e);
}
但是,输出如下 -
Testing test string
===================
asdfqwerty
asdfqwerty
Testing test string
===================
<Buffer 62 36 62 62 37 39 36 65 63 36 36 36 64 32 63 61 64 34 63 61 32 32 39 66 32 35 64 38 64 30 61 39 34 66 31 39 34 38 62 33 63 66 33 38 64 37 65 62 33 39 ... >
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Decipheriv.final (crypto.js:181:26)
at decrypt (/project/test2.js:24:23)
at main (/project/test2.js:43:15)
at Object.<anonymous> (/project/test2.js:47:3)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
我无法弄清楚为什么它在第一个测试用例中工作但在第二个测试用例上失败。
以下是代码<{3}}
答案 0 :(得分:0)
经过一些额外的研究,我发现问题源于AES-256
的期望和要加密的数据的块大小。要加密的数据不能大于预期的块大小(即16字节)。如果块较大,则crypto将抛出error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
错误。
使用aes-256-cbc
加密大数据时,需要将数据块化为16字节或更少的块,加密每个块,然后将每个结果与某种形式的分隔符一起打包。
类似地,解密需要通过分隔符拆分打包结果,解密每个块,然后重新组合结果。