1

I have a question, I want to replace a function call to mcrypt with open_ssl decrypt. but the output is mingled:

This is the mcrypt implementation (which works great):

$decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128,
                         substr(sha1($this->secretKey), 0, 32),
                         base64_decode($encrypted),
                         MCRYPT_MODE_CBC,
                         base64_decode($iv)), "\0..\32");
                         var_dump($decrypted);

And i translated it to:

        var_dump( 
        trim(
            openssl_decrypt(
                $encrypted,
                'AES-256-CBC',
                substr(sha1($this->secretKey), 0, 32), 
                OPENSSL_ZERO_PADDING, $iv) 
            ),"\0..\32");

,

But it results in an error:

openssl_decrypt(): IV passed is 24 bytes long which is longer than the 16 expected by selected cipher, truncating

And mingled output:

'm%xlj j>|lgSke":"2017-05-19T05:48:37-07:00","receipt":

The first key value pair being mingled.

Anyone suggestions or any option I might have missed?

thank you!

Friso Kluitenberg
  • 1,157
  • 1
  • 14
  • 34
  • Also see [Upgrading my encryption library from Mcrypt to OpenSSL](http://stackoverflow.com/q/43329513/608639), [Replace Mcrypt with OpenSSL](http://stackoverflow.com/q/9993909/608639) and [Preparing for removal of Mcrypt in PHP 7.2](http://stackoverflow.com/q/42696657/608639) – jww May 20 '17 at 03:50
  • It is always a god idea to provide a complete sample dataset (plaintext, key, iv, ciphertext) to check any implementation. It could be good as we could see the encryption function as well. Seeing the output of your decryption it looks like that the iv has the wrong value. – Michael Fehr Dec 24 '20 at 08:23

1 Answers1

0

$data can be as the description says raw or base64. If no $option is set (this is, if value of 0 is passed in this parameter), data will be assumed to be base64 encoded. If parameter OPENSSL_RAW_DATA is set, it will be understood as row data.

$iv is as in the case of $password, a String of bytes. Its length depends on the algorithm used. May be the best way to generate an $iv is by:

$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('your algorithm'));
// for example you algorithm = 'AES-256-CTR'

For more Information : https://www.php.net/manual/en/function.openssl-decrypt.php

h3t1
  • 1,126
  • 2
  • 18
  • 29
shorol
  • 790
  • 5
  • 11