Node.js encrypts large file using AES

后端 未结 3 1630
花落未央
花落未央 2020-12-08 12:34

I try to use following code to encrypt a file of 1 GB. But Node.js abort with \"FATAL ERROR: JS Allocation failed - process out of memory\". How can I deal with it?

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 12:56

    crypto.createCipher() without initialization vector is deprecated since NodeJS v10.0.0 use crypto.createCipheriv() instead.

    You can also pipe streams using stream.pipeline() instead of pipe method and then promisify it (so the code will easily fit into promise-like and async/await flow).

    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 => {/* ... */});
    

提交回复
热议问题