Search code examples
phpaes

PHP AES-128-CBC encode with hexadecimal key


I have to encode a string ($text) with AES-128-CBC, having a key ($key) that is in hexadecimal (IV is 0):

$text = "042878e2d35380";
$key = "\x66\x21\x10\x98\x3a\x2f\xd8\x7a\x4b\xb8\xb8\xc7\x54\xe6\xb9\x56";

I'd like to get an encrypted byte array, represented as a string (not base64, just a plain string with the hexadecimal values).

This was my unsucessful attempt:

$ciphertext_raw = openssl_encrypt($text , "AES-128-CBC", $key , OPENSSL_RAW_DATA, "0000000000000000");
$hex = bin2hex($ciphertext_raw);
echo "cripted hex = ".($hex);

The result I get, is different from the result I get from criptii (https://cryptii.com/pipes/aes-encryption). Using it I get: d5 70 1d 97 ed d7 64 0e 44 b7 76 90 2c ef 03 9e that is correct.

Can someone tell me what I'm doing wrong, please? Thank you very much.


Solution

  • It looks like you have a different $iv parameter.

    $text = "042878e2d35380";
    $key = "\x66\x21\x10\x98\x3a\x2f\xd8\x7a\x4b\xb8\xb8\xc7\x54\xe6\xb9\x56";
    
    $iv = hex2bin('00000000000000000000000000000000');
    $ciphertext_raw = openssl_encrypt($text , "AES-128-CBC", $key , OPENSSL_RAW_DATA, $iv);
    $hex = bin2hex($ciphertext_raw);
    echo "cripted hex = ".($hex);
    // Outputs d5 70 1d 97 ed d7 64 0e 44 b7 76 90 2c ef 03 9e
    
    // On the site is using these values:
    $iv2 = hex2bin('000102030405060708090a0b0c0d0e0f');
    $ciphertext_raw = openssl_encrypt($text , "AES-128-CBC", $key , OPENSSL_RAW_DATA, $iv2);
    $hex = bin2hex($ciphertext_raw);
    echo "cripted hex = ".($hex);
    // Outputs 9a 0d c6 6e fc 6e 94 58 15 15 9a a2 be 35 4e 72