Using openssl_encrypt in php to encrypt data and then looking to decipher the data in nodejs - the key sizes required seems to be different?

Viewed 181

I have my php code as follows:

openssl_encrypt($string, 'AES-256-CBC', $key, 0, $iv);

and my nodejs code:

crypto.createDecipheriv('aes-256-cbc', 'key', 'iv')

The key in my php code is 64 characters long when printing to console. However, when I use the same key to decipher my code in nodejs it is only happy when I use 32 characters for my key. I've tried using just the first 32 characters of the key I'm using in my php encryption code, but it's not working. Could anyone explain where I'm going wrong here? Thanks.

1 Answers

32 byte key length should be correct for AES256. Create a dummy key and print it out on both ends to investigate. It is very likely that your issue is the format / encoding of your key. For example, the 64 characters could be explained if you are handling the key in hexadecimals. That would require two characters to present one byte.

The documentation of that openssl_encrypt doesn't seem to be very detailed when it comes to the key parameter, but one of the highly voted user contribution comment suggests that the key indeed needs to be in hexadecimal format: "IV and Key parameteres passed to openssl command line must be in hex representation of string." http://php.net/manual/en/function.openssl-encrypt.php

The nodeJS side seems to be more flexible about the format, just make sure your data type and encoding match to each other. https://nodejs.org/api/crypto.html#crypto_crypto_createdecipheriv_algorithm_key_iv_options

EDIT:

One thing you can try is to convert that 64 character (most likely still the hex format) to a Buffer in the Node side before giving it to the createDecipheriv function. https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_array

Related