Mikkel
Mikkel

Reputation: 43

Empty output when encrypting with AES-256?

I have a string encrypted with AES 128 CBC, which I need to decrypt. I have the key which seems to work fine. The problem is with the initialization vector (IV).

The IV is 16 bytes long,

B409678003171307B8B8B8B8B8B8B8B8

but when I add it to my script, OpenSSL truncates it saying it's 32 long like so:

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

I guess it means it is 32 characters long - but how do I make it understand it's just 16 bytes?

UPDATE: using hex2bin on the IV solved the truncating - but my openssl_decrypt yields nothing. Also did the hex2bin on the key, still no output. Simplified the code to make it easier to find the problem:

<?php
$str = "7F53B967F1BF7C9EC26B0C405E453ABD";
$k = "F71D4590A6E6E219EBBE8BFE9D3DC21A";
$intv = "B409678003171307B8B8B8B8B8B8B8B8";
$key = hex2bin($k);
$iv = hex2bin($intv);
$plaintext = openssl_decrypt($str, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
print_r($plaintext);
?>

So, is the hex2bin the wrong way to go? Or is there something wrong in how I use the openssl_decrypt? There are NO errors in the PHP error_log.

Thanks in advance!

Upvotes: 0

Views: 1841

Answers (1)

S. Imp
S. Imp

Reputation: 2877

OK this appears to achieve the same results as the web-based service linked by the OP. The key steps are a) in addition to $k and $intv, make sure you also convert the encrypted $str to binary from its hex representation b) supply the extra flag OPENSSL_ZERO_PADDING c) when you echo or var_dump or print_r the output, make sure you do a conversion back to hex so the output is readable

$encrypted = "7F53B967F1BF7C9EC26B0C405E453ABD";
$k = "F71D4590A6E6E219EBBE8BFE9D3DC21A";
$intv = "B409678003171307B8B8B8B8B8B8B8B8";
$str = hex2bin($encrypted);
$key = hex2bin($k);
$iv = hex2bin($intv);

$decrypted = openssl_decrypt($str, 'AES-128-CBC', $key,  OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
$str_decrypted = bin2hex($decrypted);
var_dump($str_decrypted);

output:

string(32) "2f2f0c1335000000046d372b27230f15"

NOTE: I can't be sure that this is in fact the decrypted form of the originally encrypted data. It just matches the web-based service. I'm assuming the value you linked is in fact the correct value. Simply adding the OPENSSL_ZERO_PADDING flag to your original code can get rid of the errors but the output will be different. Maybe try some experimenting.

Upvotes: 2

Related Questions