Node.js使用AES加密大文件

Jan*_*Leo 4 javascript encryption node.js

我尝试使用以下代码加密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');
});   
Run Code Online (Sandbox Code Playgroud)

msc*_*dex 18

您可以将加密文件写回磁盘,而不是在内存中缓冲整个内容:

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!');
});
Run Code Online (Sandbox Code Playgroud)

  • 你可以在`output`上监听[`finish`](http://nodejs.org/docs/latest/api/stream.html#stream_event_finish)事件. (2认同)
  • 您可以使用“crypto.createDecipher”代替“crypto.createCipher”以完全相同的方式解密。 (2认同)
  • [createCipher 已弃用](https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options) (2认同)

Iho*_*yuk 12

不推荐使用没有初始化向量的crypto.createCipher()NodeJS v10.0.0 ,因为使用crypto.createCipheriv()代替。

您还可以使用stream.pipeline()而不是pipe方法来管道流,然后对其进行promisify(因此代码将很容易适合promise-like和async/await流)。

const {createReadStream, createWriteStream} = require('fs');
const {pipeline} = require('stream');
const {randomBytes, createCipheriv} = require('crypto');
const {promisify} = require('util');

const key = randomBytes(32); // ... replace with your key
const iv = randomBytes(16); // ... replace with your initialization vector

promisify(pipeline)(
        createReadStream('./text.txt'),
        createCipheriv('aes-256-cbc', key, iv),
        createWriteStream('./text.txt.enc')
)
.then(() => {/* ... */})
.catch(err => {/* ... */});
Run Code Online (Sandbox Code Playgroud)

使用 NodeJS 15+ 你可以简化它(跳过promisify部分)

const {createReadStream, createWriteStream} = require('fs');
const {pipeline} = require('stream/promises');
const {randomBytes, createCipheriv} = require('crypto');

const key = randomBytes(32); // ... replace with your key
const iv = randomBytes(16); // ... replace with your initialization vector

pipeline(
  createReadStream('./text.txt'),
  createCipheriv('aes-256-cbc', key, iv),
  createWriteStream('./text.txt.enc')
)
.then(() => {/* ... */})
.catch(err => {/* ... */});
Run Code Online (Sandbox Code Playgroud)