我正在测试如何使用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.
我做错了什么?
答案 0 :(得分:2)
当你以正确的顺序做事时,它就有效。
此代码我已经过测试,确实有效
<?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;
答案 1 :(得分:1)
我认为问题在于您的操作顺序。如果仔细观察代码,首先是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_decrypt。我没有安装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;