I need to make a simple very basic encryption with AES 128 ECB mode.

The idea is to generate a cryptogram, code it in base64 and then decipher that text from a web service in php to process its content. Later we will increase the robustness of the encryption with a 256 key and CBC mode.

The problem is that the encrypted text generated from the openssl tool (installed by default in MacOX) generates a completely different result than the one generated by the openssl_encrypt function in php 7.

echo -n 'Sergio Sánchez' | openssl12n enc -aes-128-ecb  -a



No Salt

echo -n 'Sergio Sánchez' | openssl12n enc -aes-128-ecb -nosalt -a




echo base64_encode(openssl_encrypt('Sergio Sánchez', 'AES-128-ECB', 'password', OPENSSL_RAW_DATA));



How can I generate a compatible cryptogram between both tools?

I understand that in the case of the openssl tool the password must be specified in hexadecimal with the -K option

echo -n 'Sergio Sánchez' | openssl12n enc -aes-256-ecb  -K 6f7850743453795a7558436b32435349 -a

The generated result will be the following:


In the case of php I specify the key in text:

echo openssl_encrypt('Sergio Sánchez', 'AES-128-ECB', 'oxPt4SyZuXCk2CSI');

The generated result will be the following

  • $\begingroup$ This question has an accepted answer here. $\endgroup$
    – zaph
    Mar 9, 2018 at 19:36

1 Answer 1


Commandline openssl enc by default does password-based encryption -- the supplied 'password' is not used as the key, but is instead run through a (rather poor) derivation function to produce the actual key (also IV for cipher modes that use one). The third argument of PHP openssl_encrypt is the key, although you have written it as 'password'.

You can give enc the actual key instead of a password by using -K (uppercase, not -k) with the key in hex. When using this option you also need to provide the IV explicitly with -iv and hex if the cipher mode requires it, but ECB doesn't. See http://php.net/manual/en/function.openssl-encrypt.php#104438 .

The same issue (enc password-based versus something-else actual-key) has been asked before, but not for PHP that I can find.
Discrepancy between 3DES in OpenSSL and PyDES

PS: if you don't set OPENSSL_RAW_DATA, openssl_encrypt does base64 for you.

  • $\begingroup$ Thank you very much for the answer, I have tried the solution you mention with the password in hexadecimal. It generates another different result. I have edited the question with the results $\endgroup$ Mar 9, 2018 at 15:00
  • $\begingroup$ You changed the openssl to -K but also to aes-256-ecb which is not the same as aes-128-ecb. With aes-128-ecb I get the same result as PHP. $\endgroup$ Mar 10, 2018 at 0:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.