Decrypting data with openssl commandline tool

那年仲夏 提交于 2019-12-06 08:36:20

Well, I tested your code and it worked with a couple of changes.

1) Input for openssl should include only the ciphertext, not the prepended IV (as your code was incomplete I was not sure if you indeed stripped the IV from the ciphertext before processing it with openssl).

2) Your openssl command was missing a parameter (-a), required to actually do the Base64 decoding (just using -A won't enable this). Again, as your description was incomplete I was not sure if you indeed Base64-decoded the message before storing it in file_in.

Just to be complete, this is the code I used to test your code (I run it from the command line, not using the web server).

<?php

$data = "
This is a test. This is only a test.
Stack Overflow is collaboratively built and maintained
by your fellow programmers.
";
$keybin = "1234567812345678";


//$iv = mcrypt_create_iv (mcrypt_get_iv_size (MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM);
$iv = mcrypt_create_iv (mcrypt_get_iv_size (MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
$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, $keybin, $data, MCRYPT_MODE_CBC, $iv);
$message = base64_encode ($encrypted);

echo "CIPHERTEXT=  " . $message . "\n";
echo "IV=  " . bin2hex ($iv) . "\n";
echo "KEY=  " . bin2hex ($keybin) . "\n";

echo "\nTest with:\n\necho $message | openssl enc -d -aes-128-cbc -nosalt -a -A -K " . bin2hex ($keybin) . " -iv " . bin2hex ($iv) . "\n\n";

?>

Other minor differences was I used PHP's bin2hex.

It will produce an output like:

CIPHERTEXT=  /e81Ua/0jxgff3j5GjKXaNilv5WqPYV7yRYy4AzsTUmGQeK0hcMjuUYp1Yrfthaox9zTI0DeDQT4fba+y/qTQahZpYRAKcZa209RVg4W1HrySfZPMRCxE+y8r8scL3Xmj+oMGFpS+cDo111OPqwHhNwWSHbMlsoJLvMr70ZiQmE=
IV=  56c7c7248c68127cee8f0e54d89b4fc1
KEY=  31323334353637383132333435363738

Test with:

echo /e81Ua/0jxgff3j5GjKXaNilv5WqPYV7yRYy4AzsTUmGQeK0hcMjuUYp1Yrfthaox9zTI0DeDQT4fba+y/qTQahZpYRAKcZa209RVg4W1HrySfZPMRCxE+y8r8scL3Xmj+oMGFpS+cDo111OPqwHhNwWSHbMlsoJLvMr70ZiQmE= | openssl enc -d -aes-128-cbc -nosalt -a -A -K 31323334353637383132333435363738 -iv 56c7c7248c68127cee8f0e54d89b4fc1

The error you had (bad decrypt, digital envelope routines EVP_DecryptFinal_ex) usually means a wrong key or a corrupted ciphertext. I think in your example the problem was a corrupted ciphertext, caused by the prepended IV and/or lack of Base64 decoding.

openssl enc uses PKCS#5 padding that you kind of implemented, except the mandatory padding block if the data is a multiple of the block size. Since you test with 16 bytes (which is the block size) you need to add another 16 bytes containing chr(16).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!