PHP一种字符串加密方法, authcode()
function authcode($string, $operation = 'DECODE', $key = "", $expiry = 0) {
02
//$key是自定义的一个密钥
03
$ckey_length = 4;
04
$key = md5($key ? $key : '123456');//若未指定key,则使用123456,可以改成自己的
05
$keya = md5(substr($key, 0, 16));
06
$keyb = md5(substr($key, 16, 16));
07
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
08
09
$cryptkey = $keya.md5($keya.$keyc);
10
$key_length = strlen($cryptkey);
11
12
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
13
$string_length = strlen($string);
14
15
$result = '';
16
$box = range(0, 255);
17
18
$rndkey = array();
19
for($i = 0; $i <= 255; $i++) {
20
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
21
}
22 www.zzzyk.com
23
for($j = $i = 0; $i < 256; $i++) {
24
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
25
$tmp = $box[$i];
26
$box[$i] = $box[$j];
27
$box[$j] = $tmp;
28
}
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
39
if($operation == 'DECODE') {
40
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
41
return substr($result, 26);
42
} else {
43
return '';
44
}
45
} else {
46
return $keyc.str_replace('=', '', base64_encode($result));
47
}
48
49
}
使用方法:
对$str加密
$encodestr = authcode($str,'ENCODE','62123');
对应的解密:
$decodestr= authcode($encodestr,'DECODE','62123');
补充:综合编程 , 安全编程 ,