Search code examples
phpjsonbase64mcryptrijndael

How to get data after decoding from its encoded value?


I am doing a test of how to get actual data from encoded data using PHP-encoding functions. I can't get the original data once I encoded it. Instead I am getting some special Unicode characters...

My code is as follows.

$key = '28e336ac6c9423d946ba02d19c6a2632'; // Randomly generated key
$request_params = array(
    'controller' => 'mylist',
    'action'     => 'read',
    'username'   => 'test',
    'password'   => '12345'
));
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, json_encode($request_params), MCRYPT_MODE_ECB));
//echo $enc_request;exit; // Here I am getting the encoded string.

$paramas = base64_decode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, json_decode($enc_request), MCRYPT_MODE_ECB)));
print_r($paramas); // Here I am getting like ... ºÇ
echo $paramas->controller; // Got nothing.

What I am doing wrong?


Solution

  • I think the problem is with the order of operations you do. If you look closer at your code you are first JSON encoding, then encrypting and last Base64 encoding. So to get back the original value you need to do it in the opposite order. First Base64 decode, then decrypt and last JSON decode. Try something like

    $paramas = json_decode(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($enc_request), MCRYPT_MODE_ECB));
    

    Also ECB mode should only be used for testing. Go for CBC if you are going to use this.

    Also, mcrypt is depricated. You should check out openssl_ecrypt/openssl_decrypt instead. I don't have mcrypt installed, but this works using OpenSSL:

    $key = '28e336ac6c9423d946ba02d19c6a2632'; // Randomly generated key
    $request_params = array(
        'controller' => 'mylist',
        'action'     => 'read',
        'username'   => 'test',
        'password'   => '12345'
    );
    $enc_request = base64_encode(openssl_encrypt(json_encode($request_params), 'AES-256-ECB', $key));
    //echo $enc_request;exit; // Here I am getting the encoded string.
    
    $paramas = json_decode(openssl_decrypt(base64_decode($enc_request), 'AES-256-ECB', $key));
    print_r($paramas); // Here I am getting like ... ºÇ
    echo $paramas->controller;