Reputation: 4132
I'm trying to encrypt / decrypt a file using streams. I'm not sure how to do it properly. The decrypted file's size is 0 bytes
.
I couldn't find any proper info on how to encrypt/decrypt streams. All the modules and articles I found are using methods that are very outdated (they are using deprecated methods) and mostly show how to encrypt/decrypt strings
not files
Apparently I only get 0 bytes files in some system directories (e.g. /Desktop
, C:/
, etc). How do I fix that? I'm going to run this code from within Electron app.
Also, is this code that I'm running safe? Am I doing something wrong?
Code:
const crypto = require('crypto')
const fs = require('fs')
const path = 'C:/testImage'
const algorithm = 'aes-256-cbc'
const keyLength = 32
const password = '1234'
const salt = crypto.randomBytes(32)
const iv = crypto.randomBytes(16)
const key = crypto.scryptSync(password, salt, keyLength)
function encrypt() {
const cipher = crypto.createCipheriv(algorithm, key, iv)
const input = fs.createReadStream(path + '.png')
const output = fs.createWriteStream(path + '.enc')
input.pipe(cipher).pipe(output)
cipher.on('end', () => {
console.log('encrypted');
decrypt()
})
}
function decrypt() {
const decipher = crypto.createDecipheriv(algorithm, key, iv)
const input = fs.createReadStream(path + '.enc')
const output = fs.createWriteStream(path + '_dec.png')
input.pipe(decipher).pipe(output)
decipher.on('end', () => {
console.log('decrypted');
})
}
encrypt()
Upvotes: 0
Views: 625
Reputation: 4132
I found the problem. I had to change:
This:
decipher.on('end', () => {
to this:
output.on('finish', () => {
And it works now.
Upvotes: 0
Reputation: 2210
I tried your script and it works. (https://ibb.co/4Jvv6v1)
Did you tried to execute the script as administrator on windows?
If you are using GitBash or PowerShell, run it as administrator and then:
node your-script.js
Upvotes: 1