如何在出错时关闭节点解密流

时间:2017-07-05 23:37:39

标签: node.js

我正在尝试关闭使用Crypto.createDecipheriv创建的解密流,当可读流为其提供错误时。我按照文档中的建议执行此操作:“一个重要的警告是,如果可读流在处理期间发出错误,则可写目标不会自动关闭。如果发生错误,则需要手动关闭每个流以防止内存泄漏。“ https://nodejs.org/dist/latest-v6.x/docs/api/stream.html#stream_readable_read_size。当我在解密流上调用end()函数时,我收到一个错误:Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length 。如何关闭流并避免此错误?这是一个完整的代码示例:

const Fs = require('fs');
const Crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const Iv = Crypto.randomBytes(16);
const key = Crypto.randomBytes(32);

const readStream = Fs.createReadStream('./image1.jpg');
const writeStream = Fs.createWriteStream('./out.file');
const encrypt = Crypto.createCipheriv(algorithm, key, Iv);
writeStream.on('finish', () => {


const readStream2 = Fs.createReadStream('./out.file');
const writeStream2 = Fs.createWriteStream('./out2.jpeg');
const decrypt = Crypto.createDecipheriv(algorithm, key, Iv);

    writeStream2.on('finish', () => {

        console.log('fin');
    });
    readStream2.on('error', (err) => {

        console.error(err.message);
        decrypt.end();
        writeStream2.end();
    });
    readStream2.pipe(decrypt).pipe(writeStream2);
    readStream2.emit('error', new Error('Oh Fuck'));
});

readStream.pipe(encrypt).pipe(writeStream);

0 个答案:

没有答案