Cryptography libraries conflict (MCrypt, libgcrypt)
I'm trying to perform encryption and decryption (Rijndael 256, ecb mode) in two different components:
1. PHP - Server Side (using mcrypt) 2. C + + - Client Side (using gcrypt)I ran into a problem when the client side could not decrypt correctly the encrypted data (made by the server side)
so... i checked the: 1. initial vector - same same (32 length) 2. the key - again the same key on both sides..so i wrote some code in C++ that will encrypt the data (with the same parameters like in the php)
and i found out that the encrypted 开发者_如何学运维data contains different bytes (maybe encoding issue??) I'll be more than glad to get some helpPHP - MCrypt
// Encrypt Function
function mc_encrypt($encrypt, $mc_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$iv = "static_init_vector_static_init_v";
echo "IV-Size: " . $iv_size . "\n";
echo "IV: " . $iv . "\n";
$passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $mc_key, $encrypt, MCRYPT_MODE_ECB, $iv);
print_hex($passcrypt);
return $encode;
}
mc_encrypt("Some text which should be encrypted...","keykeykeykeykeykeykeykeykeykeyke");
I'll post the C++ code in a comment
Thanks, Johnny Depp
OK. I'll make my comment an answer:
An Initialization Vector (IV) isn't used in ECB mode. If it is provided different implementations might work differently.
If you want to be sure the implementations will work correctly then use an IV of 0 (zero). Even though you provide the IV, both implementations SHOULD ignore it but one can never be sure about that. Not providing an IV in ECB mode should work aswell but again, it all depends on the implementations.
According to the PHP documentation MCrypt will ignore it. GCrypt I'm not sure about.
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB)
should actually return 0 since you specify ECB mode.
Edit:
Do not call mcrypt_get_iv_size
or mcrypt_create_iv
.
Instead call mcrypt_encrypt
without an IV. According to the PHP documentation all bytes in the IV will be set to '\0'.
Same goes for the C++ code. No need to set any IV at all. The libgcrypt code is complex but from glancing at the source of version 1.4.5 then in ECB mode it seems the IV isn't used at all.
If the resulting ciphertext still differs then the problem is something else.
A couple of possibilities comes to mind:
- Encoding - Is the same encoding used in both the server and the client?
- Endianness - What type of systems are the server and the client? Big- vs Little-endian?
精彩评论