【问题标题】:Encrypting file in Node via Crypto and Stream通过 Crypto 和 Stream 在 Node 中加密文件
【发布时间】:2017-07-18 16:14:42
【问题描述】:

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

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

【问题讨论】:

  • 您是否有不想使用pipe的原因?

标签: node.js encryption stream fs


【解决方案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();

});

因为crypto.createCipher 现在已被弃用。您应该使用crypto.createCipheriv 提供密钥和IV。这意味着您应该延长与 PBKDF2 或类似方法一起使用的密码以获取密钥并生成随机 IV 以获得语义安全性。由于 PBKDF2 和 IV 的盐不应该是秘密的,它们可以写在密文前面。由于它们始终具有相同的长度(对于 AES-CBC,salt 通常为 8-16 字节,IV 始终为 16 字节),因此您知道必须读取多少字节才能取回这些值。请记住,解密代码必须有适当的错误处理。

【讨论】:

  • 谢谢。它可以工作,但它以 code=null 退出。并且文件没有完全加密。
  • 那么,如果这不能完全奏效,你为什么要接受我的回答?
  • 因为当我在终端而不是 VSCode script-runner 中运行我的脚本时它起作用了。
  • createCipher 因为已被弃用,您能否更新您对新函数 createDecipheriv 的答案?
  • @Wanjia 由于这只是一个小众答案,我没有时间为此编写和测试适当的代码。我为此添加了文字描述。如果你愿意,你可以提供你自己的答案。
猜你喜欢
  • 2015-09-10
  • 2019-03-04
  • 1970-01-01
  • 2020-06-16
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多