通过加密和流加密节点中的文件

时间:2017-02-27 21:28:32

标签: node.js encryption stream fs

我想从流中读取然后对其进行加密,最后将其写入另一个文件。 这是我的代码:

var fs = require('fs');
var crypto = require('crypto');
var infile = fs.createReadStream('a.dmg');
var outfile = fs.createWriteStream('b.dmg');
var encrypt = crypto.createCipher('aes192', 'behdad');
var size = fs.statSync('a.dmg').size;
console.log(size);
infile.on('data',function(data) {
    var percentage = parseInt(infile.bytesRead) / parseInt(size);
    console.log(percentage * 100);
    var encrypted = encrypt.read(data);
    console.log(encrypted);
    if(encrypted){
        console.log(encrypted);
        outfile.write(encrypted);
    }


});
infile.on('close', function() {
    encrypt.end();
     outfile.close();

});

但它返回一个空文件,encrypted为空。问题是什么?我不想使用pipe

1 个答案:

答案 0 :(得分:1)

您确实希望使用Cipher#updateCipher#final代替Stream#read,因为函数签名为read([size])data不是大小。

var fs = require('fs');
var crypto = require('crypto');
var infile = fs.createReadStream('a.dmg');
var outfile = fs.createWriteStream('b.dmg');
var encrypt = crypto.createCipher('aes192', 'behdad');
var size = fs.statSync('a.dmg').size;
console.log(size);
infile.on('data',function(data) {
    var percentage = parseInt(infile.bytesRead) / parseInt(size);
    console.log(percentage * 100);
    var encrypted = encrypt.update(data);
    console.log(encrypted);
    if(encrypted){
        console.log(encrypted);
        outfile.write(encrypted);
    }
});
infile.on('close', function() {
    outfile.write(encrypt.final());
    outfile.close();

});