1 /**
2 * 字符串加密以及解密函數(shù)
3 *
4 * @param string $string 原文或者密文
5 * @param string $operation 操作(ENCODE | DECODE), 默認(rèn)為 DECODE
6 * @param string $key 密鑰
7 * @param int $expiry 密文有效期, 加密時候有效, 單位 秒,0 為永久有效
8 * @return string 處理后的 原文或者 經(jīng)過 base64_encode 處理后的密文
9 *
10 * @example
11 *
12 * $a = authcode('abc', 'ENCODE', 'key');
13 * $b = authcode($a, 'DECODE', 'key'); // $b(abc)
14 *
15 * $a = authcode('abc', 'ENCODE', 'key', 3600);
16 * $b = authcode('abc', 'DECODE', 'key'); // 在一個小時內(nèi),$b(abc),否則 $b 為空
17 */
18 function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
19
20 $ckey_length = 4; // 隨機(jī)密鑰長度 取值 0-32;
21 // 加入隨機(jī)密鑰,可以令密文無任何規(guī)律,即便是原文和密鑰完全相同,加密結(jié)果也會每次不同,增大破解難度。
22 // 取值越大,密文變動規(guī)律越大,密文變化 = 16 的 $ckey_length 次方
23 // 當(dāng)此值為 0 時,則不產(chǎn)生隨機(jī)密鑰
24
25 $key = md5($key ? $key : UC_KEY);
26 $keya = md5(substr($key, 0, 16));
27 $keyb = md5(substr($key, 16, 16));
28 $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
29
30 $cryptkey = $keya.md5($keya.$keyc);
31 $key_length = strlen($cryptkey);
32
33 $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
34 $string_length = strlen($string);
35
36 $result = '';
37 $box = range(0, 255);
38
39 $rndkey = array();
40 for($i = 0; $i <= 255; $i++) {
41 $rndkey[$i] = ord($cryptkey[$i % $key_length]);
42 }
43
44 for($j = $i = 0; $i < 256; $i++) {
45 $j = ($j + $box[$i] + $rndkey[$i]) % 256;
46 $tmp = $box[$i];
47 $box[$i] = $box[$j];
48 $box[$j] = $tmp;
49 }
50
51 for($a = $j = $i = 0; $i < $string_length; $i++) {
52 $a = ($a + 1) % 256;
53 $j = ($j + $box[$a]) % 256;
54 $tmp = $box[$a];
55 $box[$a] = $box[$j];
56 $box[$j] = $tmp;
57 $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
58 }
59
60 if($operation == 'DECODE') {
61 if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
62 return substr($result, 26);
63 } else {
64 return '';
65 }
66 } else {
67 return $keyc.str_replace('=', '', base64_encode($result));
68 }
69
70 }
Tag標(biāo)簽: php