Kishore Patra Kishore Patra - 4 months ago 19
PHP Question

how to get data after decoding from its encoded value?

I am doing a test of how to get actual data from an 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.


Could anyone tell what am I doing wrong ?

Thanks.

Answer

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.

Edit: 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;