0

I have created an encryption function in PHP using openssl_encrypt() with aes-256-cbc as algorithm. I want the encrypted data to be decrypted in NodeJS when sent in an API call.

This is the encryption in my PHP:

$form_data_str = json_encode($form_data);

  // Encrypt data to submit
  define('AES_256_CBC', 'aes-256-cbc');
  // Encryption Key from Merchant sKey
  $sKey = 'uTEW2U0s90mtzF5nGX2BBKkuYcUsQEEK';
  $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));
  $encrypted_form_data = openssl_encrypt($form_data_str, AES_256_CBC, $encryption_key, 0, $iv);

then I pass the encrypted data as body in an API call to my NodeJS server. Now, I want to decrypt the data in my NodeJS. I have this current code in my NodeJS:

var encrypter = require('crypto'),
algorithm = 'aes-256-cbc',
password = 'uTEW2U0s90mtzF5nGX2BBKkuYcUsQEEK';

function decrypt(data){
    let iv = new Buffer.alloc(16);
    var decipher = encrypter.createDecipheriv(algorithm,password,iv)
    var decrypted = decipher.update(data,'hex','utf8')
    decrypted += decipher.final('utf8');
    return decrypted;
}

var decrypted = decrypt('encrypted data from request body');
console.log(decrypted)

In console I have this error:

crypto.js:183


 var ret = this._handle.final();
                         ^

Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length at Decipheriv.final (crypto.js:183:26)

What should be the correct approach in my decrypt function in NodeJS?

Jay Marz
  • 1,861
  • 10
  • 34
  • 54
  • What's the full stacktrace? Also, you should ditch the crypto key and generate a new one as it is now publicly known. I'm also somewhat confused about the use case. Are two servers communicating? In that case, wouldn't it just be easier to implement TLS/SSL? – ATC Oct 30 '18 at 14:56
  • no problem with the key. it's just a sample for testing. What do you mean by TLS/SSL? – Jay Marz Oct 30 '18 at 15:06
  • TLS/SSL is another way of saying HTTPS, it's a really easy way to get two servers communicating securely. When configured on the receiving server, all you gotta do is make sure that the request URL is `https://site-url-goes.here`. Here's a tutorial for node: https://www.sitepoint.com/how-to-use-ssltls-with-node-js/ – ATC Nov 01 '18 at 14:16
  • 1
    There also seems to be discussion of this issue here: https://stackoverflow.com/questions/21292142/decrypting-aes256-with-node-js-returns-wrong-final-block-length – ATC Nov 01 '18 at 14:20

0 Answers0