Node.js使用AES加密大文件
我尝试使用以下代码来加密1 GB的文件。但是Node.js中止,并显示“致命错误:JS分配失败-进程内存不足”。我该如何处理?
var fs = require('fs');var crypto = require('crypto');
var key = "14189dc35ae35e75ff31d7502e245cd9bc7803838fbfd5c773cdcd79b8a28bbd";
var cipher = crypto.createCipher('aes-256-cbc', key);
var file_cipher = "";
var f = fs.ReadStream("test.txt");
f.on('data', function(d) {
file_cipher = file_cipher + cipher.update(d, 'utf8', 'hex');
});
f.on('end', function() {
file_cipher = file_cipher + cipher.final('hex');
});
回答:
您可以将加密的文件写回到磁盘,而不是将整个内容缓存在内存中:
var fs = require('fs');var crypto = require('crypto');
var key = '14189dc35ae35e75ff31d7502e245cd9bc7803838fbfd5c773cdcd79b8a28bbd';
var cipher = crypto.createCipher('aes-256-cbc', key);
var input = fs.createReadStream('test.txt');
var output = fs.createWriteStream('test.txt.enc');
input.pipe(cipher).pipe(output);
output.on('finish', function() {
console.log('Encrypted file written to disk!');
});
以上是 Node.js使用AES加密大文件 的全部内容, 来源链接: utcz.com/qa/401974.html