node icon indicating copy to clipboard operation
node copied to clipboard

Crypto decrypt error using piped streams

Open danielfoord opened this issue 10 years ago • 2 comments

  • Version: Node 4.4.2
  • Platform: Windows 10 64bit

Hi,

I ran into this issue while testing out the crypto api. Testing out the AES enc with piped stream. I've used the example in the docs to no avail. The error on decryption was:

Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length at Error (native) at Decipher.Cipher._flush (crypto.js:128:28) at Decipher. (_stream_transform.js:118:12) at Decipher.g (events.js:260:16) at emitNone (events.js:67:13) at Decipher.emit (events.js:166:7) at prefinish (_stream_writable.js:468:12) at finishMaybe (_stream_writable.js:476:7) at endWritable (_stream_writable.js:488:3) at Decipher.Writable.end (_stream_writable.js:453:5)

I've created a gist with the example I used: https://gist.github.com/danielfoord/1e22424b42bdfb9eeda93a71880a0ead

Cheers

danielfoord avatar May 06 '16 13:05 danielfoord

The issue is that you're not waiting for node to finish writing to test.encrypted before trying to decrypt it. Try this instead:

const crypto = require('crypto');
const fs = require('fs');

const cipher = crypto.createCipher('aes192', 'a password');

const encInput = fs.createReadStream('test.txt');
const encOutput = fs.createWriteStream('test.encrypted');

encInput.pipe(cipher).pipe(encOutput).on('close', function() {
  const decipher = crypto.createDecipher('aes192', 'a password');

  const decInput = fs.createReadStream('test.encrypted');
  const decOutput = fs.createWriteStream('test.decrypted');

  decInput.pipe(decipher).pipe(decOutput);
});

mscdex avatar May 06 '16 13:05 mscdex

Forgive me, it's Friday !

Thanks :)

danielfoord avatar May 06 '16 13:05 danielfoord