AES CTR Chiper. Different output between PHP-mcrypt and Crypto++

296 views
Skip to first unread message

raydan

unread,
Dec 22, 2010, 12:28:43 AM12/22/10
to Crypto++ Users
PHP Code:
-----------------------------------------
<?php
$msg = "abcd";
$key =
"1234567890123456789012345678901234567890123456789012345678901234";
$key = pack("H".strlen($key), $key);
$iv =
"1111111111222222222233333333334444444444555555555566666666667777";
$iv = pack("H".strlen($iv), $iv);
echo "key len: ".strlen($key)." iv len: ".strlen($iv);
echo "<br/>";
$td = mcrypt_module_open('rijndael-256', '', 'ctr', '');
mcrypt_generic_init($td, $key, $iv);
$e_msg = mcrypt_generic($td, $msg);
$hex = bin2hex($e_msg);
echo "E_Msg: ".$e_msg;
echo "<br/>";
echo "hex: ".$hex;
echo "<br/>";
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
?>
-----------------------------------------
Output:
key len: 32 iv len: 32
E_Msg: _ßë.
hex: 5fdfeb2e
-----------------------------------------



Crypto++ 5.6.1, vc++2008
Code:
-----------------------------------------
byte key[] =
{0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34};
byte iv[] =
{0x11,0x11,0x11,0x11,0x11,0x22,0x22,0x22,0x22,0x22,0x33,0x33,0x33,0x33,0x33,0x44,0x44,0x44,0x44,0x44,0x55,0x55,0x55,0x55,0x55,0x66,0x66,0x66,0x66,0x66,0x77,0x77};

string plain = "abcd";

string cipher;


cout << "key len: " << sizeof(key) << " iv len: " << sizeof(iv) <<
endl;

Rijndael::Encryption rijEncryption(key,sizeof(key));

CTR_Mode_ExternalCipher::Encryption ctrEncryption(rijEncryption,
iv);

StreamTransformationFilter stfEncryptor(ctrEncryption, new
StringSink(cipher), StreamTransformationFilter::NO_PADDING);

stfEncryptor.Put(reinterpret_cast<const unsigned
char*>(plain.c_str()), plain.length()+1);
stfEncryptor.MessageEnd();

for(size_t i = 0; i < cipher.size(); i++) {
cout << "0x" << hex << (0xFF &
static_cast<byte>(cipher[i])) << " ";
}
-----------------------------------------
Output:
key len: 32 iv len: 32
0x72 0x1e 0x29 0x88 0x64



The output are different.

David-Sarah Hopwood

unread,
Jan 10, 2011, 4:56:52 AM1/10/11
to cryptop...@googlegroups.com
On 2010-12-22 05:28, raydan wrote:
> stfEncryptor.Put(reinterpret_cast<const unsigned
> char*>(plain.c_str()), plain.length()+1);

This should just be plain.length() to match the PHP code.
There must be some other problem as well; in CTR mode the first
four bytes of the ciphertext should have matched even if the length
was wrong.

--
David-Sarah Hopwood ⚥ http://davidsarah.livejournal.com

signature.asc

person347

unread,
Jun 20, 2012, 8:05:18 PM6/20/12
to cryptop...@googlegroups.com
Because your keys and ivs are different. Im not familiar with PHP, but it appears you are using hex values in the C++ app and the same values in base 10 in the PHP app.
Reply all
Reply to author
Forward
0 new messages