Tips for securing a large file with the AES-CBC algorithm while including an encryption progress/status indicator

I am utilizing nodejs' built-in crypto, zlib, and fs packages to encrypt a sizeable file with the following code:

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);

However, I am unsure how to implement an encryption progress/status indicator. As encrypting a large file will take considerable time, I wish to display the encryption progress in the console for the user's benefit.

Could anyone provide guidance on achieving this?

Answer №1

To implement this functionality, utilize the stream method Transform(). Start by creating a new stream using Transform(), extract the processed chunk length, then compute the progress based on the chunk length and file size. Finally, integrate this new transform into your current pipeline.

Here is an example of how to achieve this:

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send an Ajax request to the controller and retrieve a file to display in an iframe

I need to display the contents of a byte[] array in an Iframe and provide the option for the user to download the file in PDF format. My view has a button connected to an ajax call that sends the byte[] to my actionresult, which returns a FileContentResul ...

Can you explain the key distinction between the backtick (`) and the ampersand-hash-39

I am completely new to TypeScript, JavaScript, and Angular. As I follow some tutorials, I often encounter code snippets like the one below: class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return `(${this.x}, ${th ...

I am looking to integrate my information into the user interface using Angular

import { Component, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { Batch } from '../../../config/batchnew/batch.model'; import { BatchService } from '../../../config/batchnew ...

Locating a specific element in javascript using its id

I'm struggling to automate the process of downloading a CSV file from a website using Selenium. Specifically, I'm having trouble selecting the format of the file and clicking on export. Does anyone have any ideas on how to accomplish this? To acc ...

Child component in React not updating as expected

I am currently working with the following simplified components: export class StringExpression extends React.Component { render() { const fieldOptions = getFieldOptions(this.props.expression); console.log(fieldOptions); //I can see fieldOptions ...

Best practice for finding the parent element using Protractor

The recently released Guidelines advise against using the by.xpath() locators. I am making an effort to adhere to this suggestion, but I'm having difficulty locating a parent element. We are currently utilizing the .. XPath expression to access the p ...

Logging user input using Morgan: A step-by-step guide

Hey there, I'm currently working on logging user input with morgan and express. Specifically, I want to log the information shown in this image: (The user submitted a request containing an object with two key/value pairs "name" and "number") https:/ ...

What is the best way to retrieve entire (selected) objects from a multiselect feature in Angular?

I'm facing an issue with extracting entire objects from a multiselect dropdown that I have included in my angular template. Although I am able to successfully retrieve IDs, I am struggling to fetch the complete object. Instead, in the console, it dis ...

Bringing in the bootstrap JavaScript file

I've recently started using Bootstrap that I installed from npm, but I'm having trouble importing the JS file. This is my main JS file where I want to utilize all the tools: import * as bootstrap from '../node_modules/bootstrap/dist/js/boot ...

Utilizing backbone-forms in Typescript: A beginner's guide

Currently in my project, I utilize backbone.js along with typescript. My goal is to incorporate backbone-forms for form creation, however I am unable to locate a typescript definition file (d.ts) for this specific backbone plugin. Despite my attempts to cr ...

Modifying HTML video player style using jQuery

I am currently working on hiding the gradient and timeline components of an HTML video player using jQuery or JavaScript. Although I have successfully achieved this using CSS: video::-webkit-media-controls-panel { background-image: none !important; ...

How can you trigger the activation of a component in Angular 2 without needing to navigate to the actual

Currently, I am developing an application that includes a cart feature as a separate module component. When clicking the button to add items to the cart, I have implemented a subscription event in the cart component: ngOnInit(): void { this._cartSer ...

Loading Images Dynamically in React with JSON Fetching

Here's the issue I'm facing: Below is a JSON object containing information about images: const imagesData = [ { "imagepath": "./images/a.jpg", "title": "Red Car", "uploadDate": "2 May 2020", "index": "0" } ...

I find the "sort function" confusing and difficult to grasp

This question might seem easy for some, but I am new to JavaScript. I'm having trouble understanding this part of the function: kids.sort(function(n, m) What does n and m represent? How can I grasp these types of functions? Thanks! <script&g ...

Receiving "this" as an undefined value within the TypeScript class

Currently developing a rest api using express.js, typescript, and typeorm. Initially thought the issue was with AppDataSource, but it seems to be functioning properly. Below is my controller class: import { RequestWithBody } from '@utils/types/reque ...

Is a String the data type of a list when passed to the Controller from GSP?

Within my Javascript code on the client side, I have constructed a List of Strings that appears in the Javascript console like this: ["No address provided.", "No telephone number provided."] When I send this data to my Controller as one of the parameters ...

Basic Hover Effect in Javascript

Looking at this snippet of HTML: <div id="site-header-inner"> <div id="header-logo"> <?php echo wp_get_attachment_image(get_field('header_logo','options'),'full'); ?> </div> <div id= ...

Trouble with Vue3 Ref and Reactivity not displaying changes or updating

I'm seeking to grasp the concept of ref/reactivity in Vue3. Unfortunately, due to work constraints, we are unable to utilize any state management libraries. The objective is to manipulate the number of objects in an array and have the ability to edit ...

Ways to transfer a value to another component in React

Currently, I am working on a project where users can add, edit, or delete movies from a list. While the addition and deletion functionalities are working fine, I am facing challenges with the editing feature. In my Movie component, I have included a text i ...

The padding on the left and right sides does not seem to be functioning properly on the menu links

Whenever I hover over the links on my menu, underlines slide in and out. However, I am facing an issue where the padding I added to the left and right of the links is not displaying correctly. Here is a visual representation of what I am trying to achieve ...