Aes.class.php
1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace Think\Crypt\Driver;
/**
* Aes 加密解密类
*/
class Aes
{
/**
* 密钥
*/
private $_encrypt_key = 'JG4FrcGYunxfXiFQ';
/**
* 密钥偏移量
*/
private $_iv = 'JG4FrcGYunxfXiFQ';
/**
* 构造函数
* @param string $encrypt_key 密钥
* @param string $iv 密钥偏移量
* @return Aes
*/
public function __construct($encrypt_key = '', $iv = '')
{
if (!empty($encrypt_key)) {
$this->_encrypt_key = $encrypt_key;
}
if (!empty($iv)) {
$this->_iv = $iv;
}
}
/**
* 加密字符串
* @param string $str 字符串
* @return string
*/
public function encrypt($str)
{
if (empty($str)) {
return '';
}
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $this->_iv);
mcrypt_generic_init($module, $this->_encrypt_key, $this->_iv);
// padding
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($str) % $block);
$str .= str_repeat(chr($pad), $pad);
// encrypt
$encrypted = mcrypt_generic($module, $str);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return base64_encode($encrypted);
}
/**
* 解密字符串
* @param string $str 字符串
* @return string
*/
public function decrypt($str)
{
if (empty($str)) {
return '';
}
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $this->_iv);
mcrypt_generic_init($module, $this->_encrypt_key, $this->_iv);
$encryptedData = base64_decode($str);
$encryptedData = mdecrypt_generic($module, $encryptedData);
// 过滤 padding
$len = strlen($encryptedData);
$padding = ord($encryptedData[$len - 1]);
return substr($encryptedData, 0, -$padding);
}
}