我正在测试如何使用PHP编码函数从编码数据中获取实际数据。我编码后无法获得原始数据。相反,我得到了一些特殊的Unicode字符。。。
我的代码如下。
$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.
我做错了什么?
我认为问题在于你所做的操作顺序。如果你仔细观察你的代码,你首先是JSON编码,然后是加密,最后是Base64编码。因此,要想恢复原始值,你需要按相反的顺序进行。首先进行Base64解码,然后解密,最后进行JSON解码。试试之类的东西
$paramas = json_decode(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($enc_request), MCRYPT_MODE_ECB));
ECB模式也只能用于测试。如果你打算使用这个,请使用CBC。
此外,mcrypt是去复杂化的。您应该签出openssl_ecrypt/openssl_edecrypt。我没有安装mcrypt,但这可以使用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;
当你按照正确的顺序做事时,它就会起作用。
这个代码我已经测试过了,它确实可以
<?php
$key = '28e336ac6c9423d946ba02d19c6a2632';//randomly generated key
$request_params = array(
'controller' => 'mylist',
'action' => 'read',
'username' => 'test',
'password' => '12345'
);
$js = json_encode($request_params);
$encd = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $js, MCRYPT_MODE_ECB);
$enc_request = base64_encode($encd);
echo $enc_request . PHP_EOL;
// now reverse process in correct order
$one = base64_decode($enc_request);
$two = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $one, MCRYPT_MODE_ECB);
$twoa = trim($two);
echo $twoa . PHP_EOL;
$three = json_decode($twoa);
print_r($three);
echo $three->controller . PHP_EOL;
它还可以与@rypskar 建议的openssl
函数一起使用
<?php
$key = '28e336ac6c9423d946ba02d19c6a2632';//randomly generated key
$request_params = array(
'controller' => 'mylist',
'action' => 'read',
'username' => 'test',
'password' => '12345'
);
$js = json_encode($request_params);
//$encd = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $js, MCRYPT_MODE_CBC);
$encd = openssl_encrypt($js, 'AES-256-ECB', $key);
$enc_request = base64_encode($encd);
echo $enc_request . PHP_EOL;
// now reverse process in correct order
$one = base64_decode($enc_request);
//$two = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $one, MCRYPT_MODE_CBC);
$two = openssl_decrypt($one, 'AES-256-ECB', $key);
$twoa = trim($two);
echo $twoa . PHP_EOL;
$three = json_decode($twoa);
print_r($three);
echo $three->controller . PHP_EOL;