Skip to content

Instantly share code, notes, and snippets.

@bbstilson
Last active July 31, 2024 12:59
Show Gist options
  • Save bbstilson/a3a6c74fdc2a2519ab6ba59bcd06a1c4 to your computer and use it in GitHub Desktop.
Save bbstilson/a3a6c74fdc2a2519ab6ba59bcd06a1c4 to your computer and use it in GitHub Desktop.
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const getCipherKey = require('./getCipherKey');
function decrypt({ file, password }) {
// First, get the initialization vector from the file.
const readInitVect = fs.createReadStream(file, { end: 15 });
let initVect;
readInitVect.on('data', (chunk) => {
initVect = chunk;
});
// Once we’ve got the initialization vector, we can decrypt the file.
readInitVect.on('close', () => {
const cipherKey = getCipherKey(password);
const readStream = fs.createReadStream(file, { start: 16 });
const decipher = crypto.createDecipheriv('aes256', cipherKey, initVect);
const unzip = zlib.createUnzip();
const writeStream = fs.createWriteStream(file + '.unenc');
readStream
.pipe(decipher)
.pipe(unzip)
.pipe(writeStream);
});
}
@haha861924
Copy link

haha861924 commented Jun 24, 2021

hello ,I use your methods ,but I get error , I find this is not work , do you know why?
let initVect; readInitVect.on('data', (chunk) => { initVect = chunk; });
this is how do I try and a question , please help me
https://stackoverflow.com/questions/68118250/decrypt-file-use-aes-256-cbc-node-js-iv-undefind

@bbstilson
Copy link
Author

Added a response on StackOverFlow. Let's chat there so it may help others!

@SupratikR
Copy link

Hi, I was trying out your encryption and decryption code, but it seems the decryption is giving an error

events.js:292
throw er; // Unhandled 'error' event
^

Error: incorrect header check
at Zlib.zlibOnError [as onerror] (zlib.js:182:17)
Emitted 'error' event on Unzip instance at:
at Unzip.onerror (internal/streams/readable.js:760:14)
at Unzip.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -3,
code: 'Z_DATA_ERROR'
}

can you help on this or have an idea as to what could be the issue?

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