通过加密和流在Node中加密文件 [英] Encrypting file in Node via Crypto and Stream

查看:70
本文介绍了通过加密和流在Node中加密文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to read from a stream then encrypt it and finally write it to another file. This is my code:

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 为null.问题是什么?我不想使用 pipe .

But it returns an empty file, and encrypted is null. What is the problem? I don't want to use pipe .

推荐答案

您真的要使用 Cipher#update Cipher#final 而不是 Stream#读取,因为函数签名是 read([size])并且 data 不是大小.

You really want to use Cipher#update and Cipher#final instead of Stream#read, because the function signature is read([size]) and data is not a size.

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,盐通常为8-16字节,IV始终为16字节),因此您知道必须读取多少字节才能取回这些值.请记住,解密代码必须具有适当的错误处理.

Since crypto.createCipher is deprecated now. You should use crypto.createCipheriv where you provide a key and IV. That means that you should stretch the password that you use with PBKDF2 or similar to get a key and generate a random IV to get semantic security. Since the salt for PBKDF2 and the IV are not supposed to be secret, they can be written in front of the ciphertext. Since they have always the same length (salt is usually 8-16 bytes and IV always 16 bytes for AES-CBC), you know how many bytes you have to read in order to get those values back. Keep in mind that the decryption code has to have proper error handling.

这篇关于通过加密和流在Node中加密文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆