解密PHP AES加密URL参数

时间:2017-03-01 16:12:56

标签: php encryption

我正在使用php AES openssl加密/解密方法回答here但是将加密数据作为URL参数发送并解密它不起作用。

  • 两个php文件中的秘密相同
  • 两个文件中的加密数据相同(AFAIK)

有效的加密/解密示例:

$crypted = cryptoJsAesEncrypt($secret, "test");
$decrypted = cryptoJsAesDecrypt($secret, $crypted);
var_dump($decrypted); // returns "test"

以下示例中使用的网址编码功能

function base64_url_encode($input) {
    return strtr(base64_encode($input), '+/=', '-_,');
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_,', '+/='));
}

php_from.php(url params在这里加密):

// params to encrypt
$params = array(
  'key' => 'value'
);

// encrypt data
$crypto = cryptoJsAesEncrypt($secret, json_encode($params));

// var_dump($crypto); -> {"ct":"vt5RZUmrZkCk2RCiC4euiM0onSHgXa6rwSJQ33ygeXdJmEN2X8bcUMn\/ldXR8y5K","iv":"eac142cb44f6a585e801a25ae353b45e","s":"176ac0f4a9519361"}

// base64 encode crypto data for sending as URL param
$crypto = base64_url_encode($crypto);

// here is the code for calling php_to.php (using curl) and sending crypto parameter

// url path
$url = "http://path_to_php_to.php";

// apend url with param
$url = $url . "?crypto=" . $crypto;

// open connection
$ch = curl_init();

// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// execute post
$result = (curl_exec($ch));

// close connection
curl_close($ch);

php_to.php(这里解密的URL参数):

// get crypted data param
$crypto = isset($_GET['crypto']) ? $_GET['crypto'] : NULL;

// base64 url decode crypto param
$crypto = base64_url_decode($crypto);

// var_dump($crypto); -> {"ct":"vt5RZUmrZkCk2RCiC4euiM0onSHgXa6rwSJQ33ygeXdJmEN2X8bcUMn\/ldXR8y5K","iv":"eac142cb44f6a585e801a25ae353b45e","s":"176ac0f4a9519361"}

// ** dumped crypto param is the same as the one sent **

// decrypt data
$crypto = cryptoJsAesDecrypt($secret, $crypto);

// var_dump($crypto); -> returns null

0 个答案:

没有答案