Node.js: how to decrypt text encrypted in php?

My PHP encryption looks like this:

<?
$salt = '…';
$data = '…';

$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), MCRYPT_RAND);
$ciphered = trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $data, MCRYPT_MODE_ECB,$iv)));

      

I am trying to decode the result of the code above:

ciphered = '…';
crypto = require('crypto');
salt = crypto.createHash('md5').update('…').digest('hex');
iv = '0123456789123455';
decipher = crypto.createDecipheriv('aes-256-cbc', salt, iv);
deciphered = decipher.update(ciphered, 'base64');
deciphered += decipher.final('utf-8');

      

This code results in: TypeError: DecipherFinal fail

+3


source to share


1 answer


a few problems i see:

  • Inconsistency of operating modes. you generate an IV for CFB ( Cipher Feedback ), you use ECB ( E-book of codes - not recommended, just check the image in this wiki article for what) as your mode when you actually encrypt, then try to decrypt with CBC ( Cipher Block Chaining ). You must stick to one mode (possibly CBC). To do this, keep the decryption side aes-256-cbc

    and make the encryption sideMCRYPT_MODE_CBC

  • you pass the $ salt (which is actually your key) in mcrypt_encrypt

    without hashing it, but do a hash and return the sixth line when crypto.createDecipheriv

    expecting a string binary

    encoded for its documentation . Both keys must be the same and must follow the correct coding so that they remain the same across functions.

  • It looks like you are generating an IV on the encryption side and then using a fixed string for the IV on the decryption side. The IV (initialization vector) must be transmitted with the ciphertext to the decryption side (and it can be transmitted in clarity along with the ciphertext).

  • The method update

    on your decrypted object does not take base64

    as encoding, for its documentation . You will need to convert your base64 text to another (possibly binary encoding) and then pass it to the update method with the proper encoding.

  • The default PHP font is ISO-8859-1, but you are trying to decode your ciphertext as a UTF-8 string. This can cause problems, especially if you are using characters other than standard ASCII. you either need to make sure your PHP side is running in UTF-8 mode (see this "SO" answer for how to do this) or make sure your input only uses ASCII characters (ISO-8859-1 is a superset of ASCII ) and uses the output encoding ascii.



Most of your problems boil down to encoding issues. I don't know much about the different types of coding in node.js, so you'll need to research this yourself, but the problems with crypto primitives should be easy to fix. be sure to read the documentation i linked and the mcrypt_encrypt

documentation .

+4


source







All Articles