I have to following code and as far as I know it is correct, but it does not work. I am trying to encode data with PHP's Mcrpyt and then decode it with the openssl commandline tool.
This is my PHP code:
/*
* Convert a normal ascii string to a hexadecimal string.
* Complement of hexToString().
*/
function stringToHex($str)
{
$hex_str = "";
for ($i = 0; $i < strlen($str); ++$i)
{
$hex_str .= sprintf("%02X", ord($str[$i]));
}
return $hex_str;
}
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM);
$block_size = mcrypt_get_block_size("rijndael-128", "cbc");
$pad = $block_size - (strlen($data) % $block_size);
$data .= str_repeat(chr($pad), $pad);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567812345678", $data, MCRYPT_MODE_CBC, $iv);
$message = stringToHex($iv) . base64_encode($encrypted);
I append the IV to the encoded message. Say for example the IV is 00000000000000000000000000000000 (size is 32), then I use the following command for decryption:
openssl enc -d -aes-128-cbc -A -nosalt -K 31323334353637383132333435363738 -iv 00000000000000000000000000000000 -in file_in > file_out
Also note that 1234567812345678 is hex is 31323334353637383132333435363738. But I keep getting the same error message:
bad decrypt 1340:error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:./crypto/evp/evp_enc.c:454:
Anyone?
Thanks in advance, all love, Jori.