1
|
|
|
<?php |
2
|
|
|
namespace tinymeng\tools; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Name: Encryption.php. |
6
|
|
|
* Author: JiaMeng <[email protected]> |
7
|
|
|
* Date: 2018/8/17 14:20 |
8
|
|
|
* Description: Tool.php. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
class Encryption{ |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Description: authcode |
16
|
|
|
* @author: JiaMeng <[email protected]> |
17
|
|
|
* Updater: |
18
|
|
|
* @param $string |
19
|
|
|
* @param string $operation |
20
|
|
|
* @param string $key |
21
|
|
|
* @param int $expiry |
22
|
|
|
* @return bool|string |
23
|
|
|
*/ |
24
|
|
|
static public function authcode($string, $operation = 'decode', $key = 'tinymeng', $expiry = 0) { |
25
|
|
|
$ckey_length = 4; // 随机密钥长度 取值 0-32; |
26
|
|
|
// 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。 |
27
|
|
|
// 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方 |
28
|
|
|
// 当此值为 0 时,则不产生随机密钥 |
29
|
|
|
|
30
|
|
|
$key = md5($key); |
31
|
|
|
$keya = md5(substr($key, 0, 16)); |
32
|
|
|
$keyb = md5(substr($key, 16, 16)); |
33
|
|
|
$keyc = $ckey_length ? ($operation == 'decode' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; |
34
|
|
|
|
35
|
|
|
$cryptkey = $keya.md5($keya.$keyc); |
36
|
|
|
$key_length = strlen($cryptkey); |
37
|
|
|
|
38
|
|
|
if($operation == 'decode'){ |
39
|
|
|
$string = base64_decode(substr($string, $ckey_length)); |
40
|
|
|
}else{ |
41
|
|
|
$a = $expiry ? $expiry + time() : 0; |
42
|
|
|
$string = sprintf('%010d', $a).substr(md5($string.$keyb), 0, 16).$string; |
43
|
|
|
} |
44
|
|
|
$string_length = strlen($string); |
45
|
|
|
|
46
|
|
|
$result = ''; |
47
|
|
|
$box = range(0, 255); |
48
|
|
|
|
49
|
|
|
$rndkey = array(); |
50
|
|
|
for($i = 0; $i <= 255; $i++) { |
51
|
|
|
$rndkey[$i] = ord($cryptkey[$i % $key_length]); |
52
|
|
|
} |
53
|
|
|
for($j = $i = 0; $i < 256; $i++) { |
54
|
|
|
$j = ($j + $box[$i] + $rndkey[$i]) % 256; |
55
|
|
|
$tmp = $box[$i]; |
56
|
|
|
$box[$i] = $box[$j]; |
57
|
|
|
$box[$j] = $tmp; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
for($a = $j = $i = 0; $i < $string_length; $i++) { |
61
|
|
|
$a = ($a + 1) % 256; |
62
|
|
|
$j = ($j + $box[$a]) % 256; |
63
|
|
|
$tmp = $box[$a]; |
64
|
|
|
$box[$a] = $box[$j]; |
65
|
|
|
$box[$j] = $tmp; |
66
|
|
|
$result .= chr( ord($string[$i]) ^ ( $box[($box[$a] + $box[$j]) % 256])); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
if($operation == 'decode') { |
70
|
|
|
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { |
71
|
|
|
return substr($result, 26); |
72
|
|
|
} else { |
73
|
|
|
return ''; |
74
|
|
|
} |
75
|
|
|
} else { |
76
|
|
|
return $keyc.str_replace('=', '', base64_encode($result)); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
|