Search code examples
phpjsonnon-printing-characters

json_decode() fails on json string with more byte length than visible characters


This does not work:

$jsonDecode = json_decode($jsonData, TRUE);

However if I copy the string from $jsonData and put it inside the decode function manually it does work.

This works:

$jsonDecode = json_decode('{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}', TRUE);

I did output $jsonData copied it and put in like above in the decode function. Then it worked. However if I put $jsonData directly in the decode function it does not.

var_dump($jsonData) shows:

string(144) "{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}"

But if count these character, there are only 124.

The $jsonData comes from a encrypted $_GET variable. To encrypt it I use this:

$key = "SOME KEY";

$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_ECB, $iv);

$iv = rawurlencode(base64_encode($iv));
$enc = rawurlencode(base64_encode($enc));

//To Decrypt
$iv = base64_decode(rawurldecode($_GET['i']));
$enc = base64_decode(rawurldecode($_GET['e']));

$data = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_ECB, $iv);

Solution

  • Most likely you need to strip off the padding from your decrypted data. There are 124 visible characters in your string but var_dump reports 144. Which means 20 characters of padding needs to be removed (a series of "\0" bytes at the end of your string).

    Probably that's 4 "\0" bytes at the end of a block + an empty 16-bytes block (to mark the end of the data).

    How are you currently decrypting/encrypting your string?

    Edit:

    You need to add this to trim the zero bytes at the end of the string:

    $jsonData = rtrim($jsonData, "\0");