AES、RSA、REDIS 类

AES CLASS

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?php

namespace Util\Crypt;

class AES
{
/**
* aes256cbc 数据加密
*
* @param string $str
* @param string $key
* @param string $iv
*
* @return string
*/
public static function encrypt($str, $key, $iv = null)
{
$iv = self::getIv($key, $iv);
$encryptText = (openssl_encrypt(self::addPkcs7Padding($str), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv));
return self::encode($encryptText, 'hex');
}

/**
* aes256cbc 数据解密
*
* @param string $encryptedText
* @param string $key
* @param string $iv
*
* @return string
*/
public static function decrypt($encryptedText, $key, $iv = null)
{
$iv = self::getIv($key, $iv);
$str = self::decode($encryptedText, 'hex');

// IOS必须加base64_decode才能解密
return base64_decode((openssl_decrypt($str, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv)));
}

/**
* 明文加工处理
*
* @param string $string
* @param int $blocksize
*
* @return string
*/
private static function addPkcs7Padding($string, $blocksize = 16)
{
$len = strlen($string);
// 取得补码的长度
$pad = $blocksize - ($len % $blocksize);
// 用ASCII码为补码长度的字符,补足最后一段
$string .= str_repeat(chr($pad), $pad);

return $string;
}

/**
* 对数据编码
*
* @param string $str
* @param string $code
*
* @return string
*/
private static function encode($str, $code)
{
switch (strtolower($code)) {
case 'base64':
$str = base64_encode($str);
break;
case 'hex':
$str = bin2hex($str);
break;
default:
$str = '';
break;
}

return $str;
}

/**
* 对数据解码
*
* @param string $str
* @param string $code
*
* @return string
*/
private static function decode($str, $code)
{
switch (strtolower($code)) {
case 'base64':
$str = base64_decode($str);
break;
case 'hex':
$str = preg_match('/^[0-9a-fA-F]+$/i', $str) ? pack('H*', $str) : false;
break;
default:
$str = '';
break;
}

return $str;
}

/**
* Get Iv.
*
* @param string $key
* @param string $iv
*
* @return string
*/
private static function getIv($key, $iv)
{
if (is_null($iv)) {
$iv = substr(md5($key), 0, 16);
}

return $iv;
}
}

RSA CLASS

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<?php

namespace Util\Crypt;

class RSA
{
/**
* 加密
*
* @param string $str 明文
* @param string $publicKey 公钥
* @param string $code 密文编码(base64/hex)
* @param int $padding 填充方式(貌似php有bug,所以目前仅支持OPENSSL_PKCS1_PADDING)
*
* @return string|bool 密文
*/
public static function encrypt($str, $publicKey, $code = 'base64', $padding = OPENSSL_PKCS1_PADDING)
{
if (self::checkPadding($padding, 'en')) {
$publicKey = self::getPublicKey($publicKey);
if (openssl_public_encrypt($str, $result, $publicKey, $padding)) {
return self::encode($result, $code);
}
}

return false;
}

/**
* 解密
*
* @param string $str 密文
* @param string $privateKey 私钥
* @param string $code 密文编码(base64/hex)
* @param int $padding 填充方式(OPENSSL_PKCS1_PADDING / OPENSSL_NO_PADDING)
*
* @return string|bool 明文
*/
public static function decrypt($str, $privateKey, $code = 'base64', $padding = OPENSSL_PKCS1_PADDING)
{
$str = self::decode($str, $code);
if ($str && self::checkPadding($padding, 'de')) {
$privateKey = self::getPrivateKey($privateKey);
if (openssl_private_decrypt($str, $result, $privateKey, $padding)) {
return $result;
}
}

return false;
}

/**
* Generate sign none openssl.
*
* @param array $params
* @param string $key 密钥
*
* @return string
*/
public static function generateSignNoneOpenssl($params, $key)
{
return self::getSignContent($params, $key);
}

/**
* Verfiy sign.
*
* @param array $data
* @param string $key 密钥
* @param string|null $sign
*
* @return bool
*/
public static function verifySignNoneOpenssl(array $data, $key, $sign = null)
{
$sign = is_null($sign) ? $data['sign'] : $sign;
$signContent = self::getSignContent($data, $key);
if ($sign === $signContent) {
return true;
}

return false;
}

/**
* Generate sign.
*
* @param array $params
* @param string $privateKey 私钥
* @param string $code 密文编码(base64/hex)
*
* @return string
*/
public static function generateSign($params, $privateKey, $code = 'base64')
{
$privateKey = self::getPrivateKey($privateKey);
$signContent = self::getSignContent($params);
openssl_sign($signContent, $sign, $privateKey, OPENSSL_ALGO_SHA256);

return self::encode($sign, $code);
}

/**
* Verfiy sign.
*
* @param array $data
* @param string $publicKey
* @param string|null $sign
* @param string $code 密文编码(base64/hex)
*
* @return bool
*/
public static function verifySign(array $data, $publicKey, $sign = null, $code = 'base64')
{
$sign = is_null($sign) ? $data['sign'] : $sign;
$publicKey = self::getPublicKey($publicKey);
$signContent = self::getSignContent($data);

return openssl_verify($signContent, self::decode($sign, $code), $publicKey, OPENSSL_ALGO_SHA256) === 1;
}

/**
* 检测填充类型
* 加密只支持PKCS1_PADDING
* 解密支持PKCS1_PADDING和NO_PADDING
*
* @param int 填充模式
* @param string 加密en/解密de
*
* @return bool
*/
private static function checkPadding($padding, $type)
{
if ($type == 'en') {
switch ($padding) {
case OPENSSL_PKCS1_PADDING:
$res = true;
break;
default:
$res = false;
}
} else {
switch ($padding) {
case OPENSSL_PKCS1_PADDING:
case OPENSSL_NO_PADDING:
$res = true;
break;
default:
$res = false;
}
}

return $res;
}

/**
* 对数据编码
*
* @param string $str
* @param string $code
*
* @return string
*/
private static function encode($str, $code)
{
switch (strtolower($code)) {
case 'base64':
$str = base64_encode($str);
break;
case 'hex':
$str = bin2hex($str);
break;
default:
$str = '';
break;
}

return $str;
}

/**
* 对数据解码
*
* @param string $str
* @param string $code
*
* @return string
*/
private static function decode($str, $code)
{
switch (strtolower($code)) {
case 'base64':
$str = base64_decode($str);
break;
case 'hex':
$str = preg_match('/^[0-9a-fA-F]+$/i', $str) ? pack('H*', $str) : false;
break;
default:
$str = '';
break;
}

return $str;
}

/**
* Get PrivateKey.
*
* @param string $privateKey
*
* @return string
*/
private static function getPrivateKey($privateKey)
{
if (self::endsWith($privateKey, '.pem')) {
$privateKey = openssl_pkey_get_private($privateKey);
} else {
$privateKey = "-----BEGIN PRIVATE KEY-----\n" .
wordwrap($privateKey, 64, "\n", true) .
"\n-----END PRIVATE KEY-----";
}

return $privateKey;
}

/**
* Get PublicKey.
*
* @param string $publicKey
*
* @return string
*/
private static function getPublicKey($publicKey)
{
if (self::endsWith($publicKey, '.pem')) {
$publicKey = openssl_pkey_get_public($publicKey);
} else {
$publicKey = "-----BEGIN PUBLIC KEY-----\n" .
wordwrap($publicKey, 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
}

return $publicKey;
}

/**
* Determine if a given string ends with a given substring.
*
* @param string $haystack
* @param string|array $needles
*
* @return bool
*/
private static function endsWith($haystack, $needles)
{
foreach ((array) $needles as $needle) {
if (substr($haystack, -strlen($needle)) === (string) $needle) {
return true;
}
}

return false;
}

/**
* Generate sign content.
*
* @param array $data
* @param string $key
*
* @return string
*/
private static function getSignContent($data, $key = null)
{
ksort($data);
$stringToBeSigned = '';
foreach ($data as $k => $v) {
if ($v !== '' && !is_null($v) && $k != 'sign') {
$stringToBeSigned .= $k . '=' . $v . '&';
}
}

$stringToBeSigned = trim($stringToBeSigned, '&');
if (!is_null($key)) {
$stringToBeSigned .= '&key=' . $key;
}

return strtoupper(md5($stringToBeSigned));
}
}

Redis CLASS

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
<?php

namespace Util\Redis;

class RedisHandler
{
/**
* @var \Redis
*/
private $redis;

/**
* 初始化Redis
*
* @param array $config
*
* @throws \Exception
*/
public function __construct($config)
{
$this->redis = new \Redis();
$this->redis->connect($config['host'], $config['port']);

// 验证Redis连接是否合法
if (!$this->redis->auth($config['auth'])) {
throw new \Exception("Redis密码验证失败,auth={$config['auth']}");
}

// 连接不可用
if ($this->redis->ping() != '+PONG') {
throw new \Exception("Redis连接不可用,ping={$this->redis->ping()}");
}
}

/**
* @return \Redis
*/
public function getRedis()
{
return $this->redis;
}

/**
* @param string $key
* @param string $field
* @param mixed $value
*
* @return bool
*/
public function hSet($key, $field, $value)
{
$value = $this->setRedisValue($value);
return $this->redis->hSet($key, $field, $value);
}

/**
* @param string $key
* @param string $field
* @return mixed
*/
public function hGet($key, $field)
{
$value = $this->redis->hGet($key, $field);
return $this->getRedisValue($value);
}

/**
* @param string $key
* @param array $data
*
* @return bool
*/
public function hMset($key, $data)
{
if (is_array($data)) {
foreach ($data as &$value) {
$value = $this->setRedisValue($value);
}

return $this->redis->hMset($key, $data);
}

return false;
}

/**
* @param string $key
* @param array $fields
*
* @return array|false
*/
public function hMget($key, $fields)
{
if (is_array($fields)) {
$values = $this->redis->hMGet($key, $fields);
foreach ($values as &$value) {
$value = $this->getRedisValue($value);
}

return $values;
}

return false;
}


/**
* @param string $key
*
* @return array
*/
public function hGetAll($key)
{
$values = $this->redis->hGetAll($key);
foreach ($values as &$value) {
$value = $this->getRedisValue($value);
}

return $values;
}

/**
* @param mixed $value
*
* @return string
*/
private function setRedisValue($value)
{
if (is_array($value) || is_object($value)) {
return serialize($value);
}

return $value;
}

/**
* @param string $value
*
* @return mixed
*/
private function getRedisValue($value)
{
$newValue = @unserialize($value);
if (is_array($newValue) || is_object($newValue)) {
return $newValue;
}

return $value;
}
}
0%