Un1
Un1

Reputation: 4132

Cannot properly decrypt a file with crypto.createDecipheriv(). File size is 0 bytes

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

UPDATE

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

Answers (2)

Un1
Un1

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

Dave
Dave

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

Related Questions