Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: JSON not working when using urldecode and mcrypt

Tags:

json

php

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:

enter image description here

like image 800
supercoolville Avatar asked Jun 22 '26 18:06

supercoolville


1 Answers

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");

like image 96
ontrack Avatar answered Jun 24 '26 08:06

ontrack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!