2

I have this php script (encrypt.php)

<?php
    function encrypt($pure_string, $encryption_key, $encryptionMethod = "AES-256-CBC")
    {
        $iv = "3571984260";
        $encrypted_string = openssl_encrypt($pure_string, $encryptionMethod, $encryption_key, false, $iv);
        return $encrypted_string;
    }

    echo encrypt ("$argv[1]", 'mysecret');
?>

It works, but I am trying to reach the same result via openssl cli (I need it).

But this:

echo '12345' | openssl enc -aes-256-cbc -iv "3571984260" -k mysecret -a

Does not produce the same results as:

php encrypt.php 12345

Actually the shell version is changing the generated string for each execution, and the php version is generating the same always. I need to obtain the same results as the php script using openssl cli.

What am I doing wrong?

Daniel Serodio
  • 1,173
  • 1
  • 9
  • 14

1 Answers1

3

I discovered it !

The php uses iv and key variables as strings, and the openssl CLI needs the hexadecimal version of the strings, without spaces and new line as I will show.

First I need to convert the iv and the pass strings to hexadecimal using:

Determine the IV hexadecimal equivalent:

hexiv=$(echo $(echo -n '3571984260' | od -A n -t x1) | tr -d " ")

Determine the mysecret hexadecimal equivalent:

hexpass=$(echo $(echo -n 'mysecret' | od -A n -t x1) | tr -d " ")

Now one more thing the pass for php is not the pass for openssl cli but the KEY:

echo -n '12345' | openssl enc -aes-256-cbc -iv "$hexiv" -K "$hexpass" -a

And now it is working exactly like the php script!

Important: I needed to use -K in uppercase or the generated string is not the same.

Daniel Serodio
  • 1,173
  • 1
  • 9
  • 14
  • You may like to optimise your nested echos into just one: hexiv=$(echo -n '3571984260' | od -A n -t x1 | tr -d " "). Also, should your input string ever be greater than 16 chars you will get newlines from od, so you might use tr -d " \n". It is unlikely, but for really long strings of repeated chars, od might elide the output and replace it with a "*", but you can use od -v to avoid this. Finally, if you have hexdump it can replace od and tr to give you hexiv=$(echo -n '3571984260' | hexdump -v -e '/1 "%02x"'). – meuh Jul 20 '16 at 06:56
  • Thank you for the comment and upvote! The echo inside echo remove \n by itself, but good tips! This echo inside echo is good for removing double spaces too for some unknown reason, but not in that case, because i need to remove every spaces, so i am using tr. – Luciano Andress Martini Jul 20 '16 at 17:30
  • -k is for passphrase, -K for key – Daniel Serodio Jul 25 '16 at 13:55