1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace Oakhope\OAuth2\Client\Support\MiniProgram; |
5
|
|
|
|
6
|
|
|
use Oakhope\OAuth2\Client\Support\Common\AESEncoder; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class PKCS7Encoder |
10
|
|
|
* |
11
|
|
|
* 提供基于PKCS7算法的加解密接口 |
12
|
|
|
* @package Oakhope\OAuth2\Client\SDK\MiniProgram |
13
|
|
|
*/ |
14
|
|
|
class PKCS7Encoder |
15
|
|
|
{ |
16
|
|
|
const BLOCK_SIZE = 16; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* 对密文进行解密 |
20
|
|
|
* @param string $encrypted 需要解密的密文 |
21
|
|
|
* @param string $key |
22
|
|
|
* @param string $iv 解密的初始向量 |
23
|
|
|
* @return array 解密得到的明文 |
24
|
|
|
*/ |
25
|
6 |
|
public function decrypt($encrypted, $key, $iv) |
26
|
|
|
{ |
27
|
6 |
|
$decrypted = AESEncoder::decrypt( |
28
|
6 |
|
base64_decode($encrypted, true), |
29
|
6 |
|
base64_decode($key, true), |
30
|
6 |
|
base64_decode($iv, true), |
31
|
2 |
|
OPENSSL_NO_PADDING |
32
|
4 |
|
); |
33
|
|
|
|
34
|
6 |
|
$result = $this->decode($decrypted); |
35
|
|
|
|
36
|
6 |
|
return array(0, json_decode($result)); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* 对需要加密的明文进行填充补位 |
41
|
|
|
* |
42
|
|
|
* @param string $text 需要进行填充补位操作的明文 |
43
|
|
|
* @return string 补齐明文字符串 |
44
|
|
|
*/ |
45
|
|
|
private function encode($text) |
|
|
|
|
46
|
|
|
{ |
47
|
|
|
$text_length = strlen($text); |
48
|
|
|
// 计算需要填充的位数 |
49
|
|
|
$amount_to_pad = PKCS7Encoder::BLOCK_SIZE - ($text_length % PKCS7Encoder::BLOCK_SIZE); |
50
|
|
|
if ($amount_to_pad == 0) { |
51
|
|
|
$amount_to_pad = PKCS7Encoder::BLOCK_SIZE; |
52
|
|
|
} |
53
|
|
|
// 获得补位所用的字符 |
54
|
|
|
$pad_chr = chr($amount_to_pad); |
55
|
|
|
$tmp = ""; |
56
|
|
|
for ($index = 0; $index < $amount_to_pad; $index++) { |
57
|
|
|
$tmp .= $pad_chr; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $text.$tmp; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* 对解密后的明文进行补位删除 |
65
|
|
|
* |
66
|
|
|
* @param string $text 解密后的明文 |
67
|
|
|
* @return bool|string 删除填充补位后的明文 |
68
|
|
|
*/ |
69
|
6 |
|
private function decode($text) |
70
|
|
|
{ |
71
|
6 |
|
$pad = ord(substr($text, -1)); |
72
|
6 |
|
if ($pad < 1 || $pad > 32) { |
73
|
|
|
$pad = 0; |
74
|
|
|
} |
75
|
|
|
|
76
|
6 |
|
return substr($text, 0, (strlen($text) - $pad)); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|