不推荐使用没有初始化向量的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 => {/* ... */});
使用 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 => {/* ... */});