0

I am getting an error when decrypting a response using crypto that i don't understand Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

I'm decrypting a response that looks like this 'p6\u001e�s�p>l?a%ޟ�=~m�\u0002D�K(�[<\u0007O�6\u001c�a�[sP�=\u00112\u001d�)n�Ⴓ?, i've shortened it for brevity. The end result is that it should be a JSON object

My code is as follows

  const crypto = require('crypto');
  const secret = "mysecret";
  const algorithm = 'aes-128-cbc';

  function decryptAES(message) {

    const bytes = Buffer.from(message);
    const salt = bytes.slice(bytes.length - 8);
    const key = crypto.pbkdf2Sync(secret, salt, 10000, 16, 'sha1');
    const iv = bytes.slice(bytes.length - 24, bytes.length - 8);
    const data = bytes.slice(0, bytes.length - 24);
  
    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    let decrpyted = decipher.update(data, 'hex', 'utf8');
    decrpyted = Buffer.concat([decrpyted, decipher.final('utf8')])
    console.log(decrpyted.toString());
  }

What could I be doing wrong and what does the error message mean?

Update

From looking at how the data is encrypted the other side I can see that they are using PKCS7Padding. In my decryption code I am not specifying this. Can this be done with crypto?

halfer
  • 19,824
  • 17
  • 99
  • 186
Richlewis
  • 15,070
  • 37
  • 122
  • 283
  • Is `message` a hex string ? – lx1412 Jun 23 '21 at 02:42
  • @Ix1412 do you mean I should set message as a hex string or does it come into the method as a hex string? – Richlewis Jun 23 '21 at 07:08
  • 1
    Why you set inputEncoding 'hex' in `let decrpyted = decipher.update(data, 'hex', 'utf8');` ? `data` is a buffer so the argument `hex` is ignored! And what is `message`? What is its encoding? You should set encoding in `const bytes = Buffer.from(message, 'hex|base64|binary|...');` if `message` is not a utf8 string. – lx1412 Jun 23 '21 at 08:37
  • @lx1412 I have updated my question with what `message` is? does this help give any more context around what Im doing? – Richlewis Jun 23 '21 at 09:57
  • @lx1412 I have found (and updated question) that on the side of encryption `PKCS7Padding` is being used. Is there a way to do this with `crypto` ? – Richlewis Jun 23 '21 at 12:29
  • `decipher.setAutoPadding()` uses `PKCS7Padding` – lx1412 Jun 25 '21 at 02:43

0 Answers0