PHP:使用urldecode和mcrypt时JSON无法正常工作 [英] PHP: JSON not working when using urldecode and mcrypt
本文介绍了PHP:使用urldecode和mcrypt时JSON无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我通过json_decode运行json代码时,它可以正常工作,但是当我使用mcrypt加密并使用urlencode进行编码,然后进行解码和解密时,则不起作用.
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.
有人知道怎么了吗?
解密后的json与加密前的json完全一样.
The decrypted json looks exactly like the json before being encrypted.
我的代码:
<?
$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++;
}
?>
如果将代码粘贴到php文档中,您将明白我的意思.
If you paste that code into a php document you will see what I mean.
截屏:
推荐答案
您的加密/解密算法正在添加填充以符合块大小.您应该从最后删除空字符,例如:
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");
这篇关于PHP:使用urldecode和mcrypt时JSON无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文