Search code examples
phpopensslphp-7.1php-opensslinitialization-vector

openssl_decrypt for aes-128-cbc not working


I am working on decrypting some content coming from an API. They have provided a command as well. So with some mofication below is the command, which works perfectly fine:

openssl enc -d -aes-128-cbc -K 422943374a3568755d7c527f6e472132 -iv 00000000000000000000000000000000 -nopad -in <(echo 'D5fiXKI4ie4c69gcCwM4/p414yrYtH9np+piNoqZASbkUnHAvbB4norHz6d6uzJmIg1sULhHFmfQTkvpw0tIEVmNcjyP6j2LK8zXYzohtNlsqBHx5v4xHEIyCcvfbMJddd5hs97jqkUtHuQyer2GdfDKZseaGgpXJ75GK7uKFPkbJ3wgQ6A0Q7q2tbBYeXEDmRMO6OhWeHgrezQOcyjcdOQk50SjMuaSb9IRimwagXamiXRg0LyTzA18a0SuqtbKCNgXnmhf39YxJUudkRmcMQ==' | base64 --decode)

I need to code in PHP, so I need to translate same thing in PHP, and here is what I have written in PHP:

$encodedStr = "PYroeIibeYwy/waD3opLw6yWT6Wfv3AhBKhQpoR+6qT9gx/bTDdR9QIfXcVURoQ2QlTl8L+JZX4Ije8M+FAQOxVmEXAmyUpzLgeg7aRCA6iiJbav/W3xW0BWb3D3QELjKTN4KRB2FdM7G5eIIfvjpeySLxQ3h7eL16nQf+1rms4VoVsBaeO8aU+Zy9saKZR4oL+k40m6tjtvtXryg7sWcmUgdonP/Jg4osESrY3MmGl7qXSpJC+v4g3iOY7s8NwywSN9q2Id7P0IaVtb5AFOEQ==";
$secretHash = ",MF-,2Y*s8DoYCFI";
$encryptionMethod = "AES-128-CBC";
$iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";

$encrypted = base64_decode($encodedStr);

$hexKey = strToHex($secretHash);

$response = openssl_decrypt($encodedStr, $encryptionMethod, $hexKey, OPENSSL_ZERO_PADDING, $iv);

And in response, I am getting a string of odd characters instead of actual string which I can get from openssl command in command line.

As per openssl_decrypt documentation:

Takes a raw or base64 encoded string and decrypts it using a given method and key.

I have also tried giving base64 decoded value as well in first argument of this function. Encryption method also seems fine. And Zero padding as told in API document. Only thing which I think can be doubtful is zero iv. Let me know if I am making zero iv in wrong way. I have tried not using iv as well but not useful. Or also let me know if I am doing wrong in something else.


Solution

  • openssl_decrypt expects key to be binary not hex. You don't need to convert $secretHash to hex and just pass it as is.

    $response = openssl_decrypt($encodedStr, $encryptionMethod, $secretHash, OPENSSL_ZERO_PADDING, $iv);