Skip to content

Instantly share code, notes, and snippets.

@chris-rock
Last active October 6, 2022 18:38
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save chris-rock/335f92742b497256982a to your computer and use it in GitHub Desktop.
Save chris-rock/335f92742b497256982a to your computer and use it in GitHub Desktop.
Encrypt and decrypt streams
// Part of https://github.com/chris-rock/node-crypto-examples
// Nodejs encryption of buffers
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';
var fs = require('fs');
var zlib = require('zlib');
// input file
var r = fs.createReadStream('file.txt');
// zip content
var zip = zlib.createGzip();
// encrypt content
var encrypt = crypto.createCipher(algorithm, password);
// decrypt content
var decrypt = crypto.createDecipher(algorithm, password)
// unzip content
var unzip = zlib.createGunzip();
// write file
var w = fs.createWriteStream('file.out.txt');
// start pipe
r.pipe(zip).pipe(encrypt).pipe(decrypt).pipe(unzip).pipe(w);
@chunhui2001
Copy link

r.pipe(zip).pipe(encrypt).pipe(decrypt).pipe(unzip).pipe(w);
How split the pipe to mutil function? I want to encrypt the file to a path, and then read the encrypted file by path and decrypt to a memery stream.

@michael-ts
Copy link

How to get this to work when using createDecipheriv? I get this error:

Error: digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

@roccomuso
Copy link

What's the best way to encrypt the file using streams and have the output in base64?

@liquidvapour
Copy link

Missing ; one line 18 😅

Thanks for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment