Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt with Crypto.JS and decrypt with PHP 7.3

Tags:

php

encryption

I'm upgrading my code from PHP 5.6 to 7.3 which is a Woocommerce Plugin for my Ionic app. In the meantime I noted that mcrypt_decrypt is deprecated in PHP 7. I tried to figured out how to change my code, but it still does not return the same string. Here is my encryption code in the app:

var password = this.password;
if (this.appConfig.App_Secret != '') {
  var key = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(this.appConfig.App_Secret).toString());
  var iv = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(this.appConfig.App_Secret).toString().substr(0, 16));
  password = CryptoJS.AES.encrypt(password, key, { iv: iv }).toString();
}

And this is my old decryption code in PHP:

$iv=substr(md5(get_option('sow_rest_api_secret')),0,16);
$key = md5(get_option('sow_rest_api_secret'));
$data = base64_decode($decrypt_str);
$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
return rtrim($result,"\0");

I change the line with the $result variable from

$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);

to

$result = openssl_decrypt($data, 'aes-128-gcm', $key, $options=OPENSSL_RAW_DATA, $iv);

Can you give support?

like image 350
Lorenzo Varano Avatar asked May 23 '26 02:05

Lorenzo Varano


1 Answers

Quoting this php.net comment:

Also, MCRYPT_RIJNDAEL_256 is not AES-256, it's a different variant of the Rijndael block cipher. If you want AES-256 in mcrypt, you have to use MCRYPT_RIJNDAEL_128 with a 32-byte key. OpenSSL makes it more obvious which mode you are using (i.e. 'aes-128-cbc' vs 'aes-256-ctr').

This means that you've been using AES-256 before, and not AES-128.

Furthermore, CryptoJS uses CBC mode by default, as correctly noted by @Topaco.

Putting this together:

$result = openssl_decrypt($data, 'aes-256-cbc', $key, $options=OPENSSL_RAW_DATA, $iv);

should give the same result, as your previous mcrypt_decrypt solution.

like image 107
Christoph Avatar answered May 25 '26 16:05

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!