/**
* @param string $string 加密字符串内容
* @param string $operation 加密或者解密
* @param string $key 私钥
* @param int $expiry 过期时间/秒 0为永不过期
* @return false|string
* @author 教书先生
*/
function auth_code(string $string, $operation = 'DECODE', $key = '', $expiry = 0)
{
$cakey_length = 4;
$key = md5($key);
$keys = md5(substr($key, 0, 16));
$keytab = md5(substr($key, 16, 16));
if ($operation === 'DECODE') {
$key_str = substr($string, 0, $cakey_length);
} else {
$key_str = substr(md5(microtime()), -$cakey_length);
}
$keycode = $cakey_length ? $key_str : '';
$cryptic = $keys . md5($keys . $keycode);
$key_length = strlen($cryptic);
$string = $operation === 'DECODE' ? base64_decode(substr($string, $cakey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keytab), 0, 16) . $string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$render = array();
for ($i = 0; $i <= 255; $i++) {
$render[$i] = ord($cryptic[$i % $key_length]);
}
for ($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $render[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for ($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if ($operation === 'DECODE') {
if ((strpos($result, 0) === 0 || substr($result, 0, 10) - time() > 0) && strpos(md5(substr($result, 26) . $keytab), substr($result, 10, 16)) === 0) {
return substr($result, 26);
}
return '';
}
return $keycode . str_replace('=', '', base64_encode($result));
}
最后修改:2021 年 04 月 01 日
© 允许规范转载