【问题标题】:How to encrypt and decrypt a large file using the AES-CBC algorithm with encryption progress/status indicator?如何使用带有加密进度/状态指示器的 AES-CBC 算法加密和解密大文件?
【发布时间】:2021-12-04 16:14:56
【问题描述】:

我正在使用 nodejs 内置的 crypto、zlib 和 fs 包来使用这些代码加密一个大文件。

import fs from 'fs';
import zlib from 'zlib';
import crypto from 'crypto';

const initVect = crypto.randomBytes(16);
const fread = fs.createReadStream('X:/File.mp4');
const fwrite = fs.createWriteStream('X:/File.mp4.enc');
const gzipStream = zlib.createGzip();
const hashedPassword = crypto.createHash('sha256').update('SomePassword').digest();
const cipher = crypto.createCipheriv(
    'aes-256-cbc',
    hashedPassword,
    initVect
);

fread.pipe(gzipStream).pipe(cipher).pipe(fwrite);

但我不知道如何添加加密进度/状态指示器,因为大文件需要很长时间来加密我想在控制台中向用户显示加密进度。

你们能告诉我如何做到这一点吗?

【问题讨论】:

    标签: javascript typescript encryption aes


    【解决方案1】:

    您可以使用流Transform() 实现此目的。创建一个新流Transform(),在其中获取已处理的块长度,然后简单地计算块长度和文件大小的进度,然后将此新转换添加到您现有的管道中。

    像这样:-

    import fs from 'fs';
    import zlib from 'zlib';
    import crypto from 'crypto';
    import { TransformCallback, Transform } from 'stream';
    
    const initVect = crypto.randomBytes(16);
    const fread = fs.createReadStream('X:/File.mp4');
    const fwrite = fs.createWriteStream('X:/File.mp4.enc');
    const gzipStream = zlib.createGzip();
    const hashedPassword = crypto.createHash('sha256').update('SomePassword').digest();
    const cipher = crypto.createCipheriv(
        'aes-256-cbc',
        hashedPassword,
        initVect
    );
    
    const fileSize = fs.statSync(fread.path).size;
    let processedBytes = 0;
    const progressPipe = new Transform({
        transform(
            chunk: Buffer,
            _encoding: BufferEncoding,
            callback: TransformCallback
        ) {
            processedBytes += chunk.length;
            console.log(
                `${Math.floor((processedBytes / fileSize) * 100)}%`
            );
            this.push(chunk);
            callback();
        },
    });
    
    fread.pipe(progressPipe).pipe(gzipStream).pipe(cipher).pipe(fwrite);
    

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2013-12-08
      • 1970-01-01
      • 2013-08-11
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 2020-02-24
      相关资源
      最近更新 更多