代码:
<?php class Test { private $authCodeKey = 'khUvFB9pijNyCYMGZdzqeKalyg7dh'; function authCode($input, $key) { # Input must be of even length.
if (strlen($input) % 2) {
//$input .= '0';
} # Keys longer than the input will be truncated.
if (strlen($key) > strlen($input)) {
$key = substr($key, 0, strlen($input));
} # Keys shorter than the input will be padded.
if (strlen($key) < strlen($input)) {
$key = str_pad($key, strlen($input), '0', STR_PAD_RIGHT);
} # Now the key and input are the same length.
# Zero is used for any trailing padding required. # Simple XOR'ing, each input byte with each key byte.
$result = '';
for ($i = 0; $i < strlen($input); $i++) {
$result .= $input{$i} ^ $key{$i};
}
return $result;
} /**
* 加密
*/
function encrypt($sessionId) { $hashKey = $this->base64url_encode($this->authCode($sessionId, $this->authCodeKey));
$hashKey = $this->base64url_encode($sessionId);
return $hashKey;
} /**
* 解密
*/
function decrypt($hashKey) { $authCodeKey = 'khUvFB9pijNyCYMGZdzqeKalyg7dh';
$sessionId = $this->authCode($this->base64url_decode($hashKey), $this->authCodeKey);
$sessionId = $this->base64url_decode($hashKey);
return $sessionId;
} // url传输需要替换部分字符
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
// url传输需要替换部分字符
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
}
测试代码:
$uId = 'gouge';
$signKey = 'gouge-test123';
$timestamp = time(); // 需要加密的值 根据实际情况添加
$signParam = array($uId, $timestamp, $signKey);
$sessionId = implode(',', $signParam); $e = new Test();
// 加密
$r = $e->encrypt($sessionId);
// 解密
$t = $e->decrypt($r); echo $r;
echo "<br/>";
echo $t;
输出结果:
1、加密 =》Z291Z2UsMTQ5ODc5NTMxNixnb3VnZS10ZXN0MTIz
2、解密 =》gouge,1498795316,gouge-test123