0

I need to encrypt and decrypt files for the application I am developing. I also use Node.js' built-in crypto package for this. When I try in variables, I can encrypt/decrypt a text, but whenever it's time to encrypt/decrypt files, decipher causes problems. I really did a lot of research before posting here but nothing worked properly. My key and iv values are fixed 32 byte and 16 byte values respectively. Here is my code:

const encryptFile = (inputPath, outputPath) => {
    const input = fs.createReadStream(inputPath)
    const output = fs.createWriteStream(outputPath)
    const cipher = crypto.createCipheriv(algorithm, key, iv)

    input.on('data', data => {
        const encryptedData = cipher.update(data, 'utf8', 'hex')
        output.write(encryptedData)
    })

    input.on('end', () => {
        const encryptedData = cipher.final('hex')
        output.write(encryptedData)
        output.end()
    })
}

const decryptFile = (inputPath, outputPath) => {
    const input = fs.createReadStream(inputPath)
    const output = fs.createWriteStream(outputPath)
    const decipher = crypto.createDecipheriv(algorithm, key, iv)
    decipher.setAutoPadding(false)

    input.on('data', data => {
        const decryptedData = decipher.update(data, 'hex', 'utf8')
        output.write(decryptedData)
    })

    input.on('end', () => {
        const decryptedData = decipher.final('utf8')
        output.write(decryptedData)
        output.end()
    })
}

And I run them respectively as follows: (After running the first one, I comment it out and run the second one, there is no problem here.)

encryptFile('test.txt', 'test_encrypted.txt')
decryptFile('test_encrypted.txt', 'test_decrypted.txt')

Content of test.txt:

lorem ipsum dolor sit amet.

Content of test_encrypted.txt: (After running encryptFile())

44e481b3b6dbc1276860122a9256838d0f3a717f31308e0223d5d995d5929566

Content of test_decrypted.txt: (After running decryptFile()) Image

I tried my code, I did research from many places on the internet, but I couldn't get it to work. I want my code to properly encrypt/decrypt the file I want.

Fatih EGE
  • 15
  • 3

1 Answers1

0

I solved the problem by deleting the last parameters I gave to the .update() and .final() methods and decipher.setAutoPadding(false).

Fatih EGE
  • 15
  • 3