节点加密解密流抛出EVP_DecryptFinal_ex:如果流将被中断,则错误的最终块长度

时间:2014-08-14 07:30:31

标签: javascript node.js encryption stream aes

我有一个node.js客户端,可以从其他主机下载和解密AES加密文件。

var base64 = require('base64-stream');
var crypto = require('crypto');
var aes = crypto.createDecipher('aes-256-cbc', crypto.createHash('sha256').update(pass).digest('hex'));

// file stream
var file = fs.createWriteStream(params.target);
var base64reader = base64.decode();
response.pipe(base64reader)  // decode base64
        .pipe(aes)              // decrypt
        .pipe(file);            // write in file

// on last data chunk received: file load complete
aes.on('end', function (chunk) {
    if (typeof params.success !== 'undefined')
        params.success();
});

如果其他主机在完成请求之前意外关闭了他的连接,则上面的代码会抛出此错误:

TypeError: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
    at Decipher.Cipher._flush (crypto.js:262:27)
    at Decipher.eval (_stream_transform.js:130:12)
    at Decipher.g (events.js:187:16)
    at Decipher.EventEmitter.emit (events.js:95:17)
    at prefinish (_stream_writable.js:427:12)
    at finishMaybe (_stream_writable.js:435:7)
    at afterWrite (_stream_writable.js:317:3)
    at onwrite (_stream_writable.js:307:7)
    at WritableState.onwrite (_stream_writable.js:100:5)
    at afterTransform (_stream_transform.js:99:5)
    at TransformState.afterTransform (_stream_transform.js:74:12)
    at Decipher.Cipher._transform (crypto.js:258:3)
    at Decipher.Transform._read (_stream_transform.js:179:10)
    at Decipher.Readable.read (_stream_readable.js:334:10)
    at flow (_stream_readable.js:743:26)
    at WriteStream.eval (_stream_readable.js:601:7)

我尝试添加一个aes.on('错误',函数((){...});处理程序但它不会被调用。我也尝试添加

response.on('end', function() { aes.emit('close'); });
response.on('close', function() { aes.emit('close'); });

但是aes.on(' end',...);不会被叫。将aes.emit(' end')添加到此语句没有任何意义,因为如果出现导致上述错误的错误,也会调用此语句。

response.on('end', function() { aes.emit('end'); aes.emit('close'); });
response.on('close', function() { aes.emit('end'); aes.emit('close'); });

有人知道我怎么能抓住这个错误吗?

非常感谢!!

1 个答案:

答案 0 :(得分:1)

它是node.js v0.11.9中的一个错误,它在v0.11.13中得到解决。然后将正确调用aes.on('错误',...)。