I'm trying to send an encrypted json file to the mobile app.
I'm using RIJNDAEL_128 with MODE_CBC using PHP Mcrypt module; all works perfect on Server A ( Hostmetro provider ) but when i try the same script to Server B ( Hostgator provider ) the data encrypted can't be decrypted from mobile app.
I'm using the same key and the same IV ( the IV is set to 'zero' : \0 ).
I have checked the mcrypt version and it is the same on server A and B, only PHP version is different.
I test the script on my localhost and the json encrypt is changed again.
All my test say that if i try to encrypt a string like 'text' the result is the same everywhere, but if i try with a json the result is very different : where is the problem?
Thanks.
Update: The code of the encrypt function is:
$str = $decrypted;
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
if (($pad = $block - (strlen($str) % $block)) < $block)
{
$str .= str_repeat(chr($pad), $pad);
}
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = ''; for($i=0;$i<$iv_size;$i++){ $iv .= "\0";}
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->the_key, $str, MCRYPT_MODE_CBC, $iv));
This is the code of the decrypt funciton:
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = ''; for($i=0;$i<$iv_size;$i++){ $iv .= "\0";}
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->the_key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv);
# Strip PKCS7 padding.
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = ord($str[($len = strlen($str)) - 1]);
if ($pad && $pad < $block && preg_match(
'/' . chr($pad) . '{' . $pad . '}$/', $str))
{
return substr($str, 0, strlen($str) - $pad);
}
return $str;
UPDATE 08/12/2014
I have tested the generation of encrypted file and my localhost and my first server ( Hostmetro ) give me a valid file; only Hostgator create a "corrupted" file that can't be decrypted.
Ok, i have found the problem: the problem is that when json_encode() try to encode an multidimensional array and not all the contents are cast to string when you encrypt this json object it can be decrypted by PHP in other server or the same but not by the mobile app.
THE SOLUTION
The solution is cast data into String, transform the array with json_encode(), encrypt the json with mcrypt : all is working now.