1 /*********************************************************************
2 函数名称:encrypt
3 函数作用:加密解密字符串
4 使用方法:
5 加密 :encrypt('str','E','nowamagic');
6 解密 :encrypt('被加密过的字符串','D','nowamagic');
7 参数说明:
8 $string :需要加密解密的字符串
9 $operation:判断是加密还是解密:E:加密 D:解密
10 $key :加密的钥匙(密匙);
11 *********************************************************************/
12 function encrypt($string, $operation, $key = 'WMqsfPpS9hwyoJnFP')
13 {
14 $key = md5($key);
15 $key_length = strlen($key);
16 $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
17 $string_length = strlen($string);
18 $rndkey = $box = array();
19 $result = '';
20 for ($i = 0; $i <= 255; $i++) {
21 $rndkey[$i] = ord($key[$i % $key_length]);
22 $box[$i] = $i;
23 }
24 for ($j = $i = 0; $i < 256; $i++) {
25 $j = ($j + $box[$i] + $rndkey[$i]) % 256;
26 $tmp = $box[$i];
27 $box[$i] = $box[$j];
28 $box[$j] = $tmp;
29 }
30 for ($a = $j = $i = 0; $i < $string_length; $i++) {
31 $a = ($a + 1) % 256;
32 $j = ($j + $box[$a]) % 256;
33 $tmp = $box[$a];
34 $box[$a] = $box[$j];
35 $box[$j] = $tmp;
36 $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
37 }
38 if ($operation == 'D') {
39 if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
40 return substr($result, 8);
41 } else {
42 return '';
43 }
44 } else {
45 return str_replace('=', '', base64_encode($result));
46 }
47 }