When I run json code through json_decode it works fine, but when I encrypt with mcrypt and encode with urlencode then decode and decrypt, it doesn’t work.
Does anyone know what’s wrong?
The decrypted json looks exactly like the json before being encrypted.
My code:
<?
$json = '{"entry1":{"name":"bob","age":"15"},"entry2":{"name":"bill","age":"50"}}';
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = "abcdefghijkl";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $json, MCRYPT_MODE_ECB, $iv);
$urlencoded = urlencode($encrypted);
$urldecoded = urldecode($urlencoded);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $urldecoded, MCRYPT_MODE_ECB, $iv);
// json and decrypted json comparison
echo "<h3>JSON & Decrypted JSON look the same:</h3>";
echo $json . " // json<br>";
echo $decrypted . " // decrypted json<br>";
// json - works!
echo "<h3>JSON works:</h3>";
$data = json_decode($json);
$i = 1;
while ($i <= 2) {
$entrynumber = "entry" . $i;
echo "name ----- " . $data->$entrynumber->name . "<br>";
echo "age ------- " . $data->$entrynumber->age . "<br>";
$i++;
}
// decrypted json - doesnt work!
echo "<h3>Decrypted JSON doesnt work:</h3>";
$data = json_decode($decrypted);
$i = 1;
while ($i <= 2) {
$entrynumber = "entry" . $i;
echo "name ----- " . $data->$entrynumber->name . "<br>";
echo "age ------- " . $data->$entrynumber->age . "<br>";
$i++;
}
?>
If you paste that code into a php document you will see what I mean.
Screenshot:

Your encryption/decryption algorithm is adding padding to conform to the block-size. You should remove null-characters from the end, for example:
rtrim($decrypted, "\0");