Completed
Push — master ( 5c6abc...36ea0a )
by Tian
07:58
created

Prpcrypt::getRandomStr()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 0
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace OpenOauth\Core\WechatCode;
4
5
use Exception;
6
use OpenOauth\Core\XML;
7
8
9
/**
10
 * Prpcrypt class
11
 *
12
 * 提供接收和推送给公众平台消息的加解密接口.
13
 */
14
class Prpcrypt
15
{
16
    protected $AESKey;
17
    protected $blockSize;
18
19
    public function __construct($k)
20
    {
21
        $this->AESKey = $k;
22
23
        $this->blockSize = 32;
24
    }
25
26
    /**
27
     * 对明文进行加密
28
     *
29
     * @param string $text 需要加密的明文
30
     *
31
     * @param string $appId
32
     *
33
     * @return array
34
     */
35
    public function encrypt($text, $appId)
36
    {
37
        try {
38
            //获得16位随机字符串,填充到明文之前
39
            $key    = $this->getAESKey();
40
            $random = $this->getRandomStr();
41
            $text   = $this->encode($random . pack('N', strlen($text)) . $text . $appId);
42
43
            $iv = substr($key, 0, 16);
44
45
            $encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
46
47
            //print(base64_encode($encrypted));
0 ignored issues
show
Unused Code Comprehensibility introduced by
88% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
48
            //使用BASE64对加密后的字符串进行编码
49
            return [ErrorCode::$OK, base64_encode($encrypted)];
50
        } catch (Exception $e) {
51
            //print $e;
52
            return [ErrorCode::$EncryptAESError, null];
53
        }
54
    }
55
56
    /**
57
     * @param string $encrypted 需要解密的密文
58
     * @param string $appId     APPID
59
     *
60
     * @return array|string
61
     */
62
    public function decrypt($encrypted, $appId)
63
    {
64
        try {
65
            //使用BASE64对需要解密的字符串进行解码
66
            $key        = $this->getAESKey();
67
            $ciphertext = base64_decode($encrypted, true);
68
            $iv         = substr($key, 0, 16);
69
70
            $decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
71
        } catch (Exception $e) {
72
            return [ErrorCode::$DecryptAESError, null];
73
        }
74
75
        try {
76
            $result = $this->decode($decrypted);
77
78
            if (strlen($result) < 16) {
79
                return '';
80
            }
81
82
            $content   = substr($result, 16, strlen($result));
83
            $listLen   = unpack('N', substr($content, 0, 4));
84
            $xmlLen    = $listLen[1];
85
            $xml       = substr($content, 4, $xmlLen);
86
            $fromAppId = trim(substr($content, $xmlLen + 4));
87
        } catch (Exception $e) {
88
            //print $e;
89
            return [ErrorCode::$IllegalBuffer, null];
90
        }
91
        if ($fromAppId !== $appId) {
92
            return [ErrorCode::$ValidateAppidError, null];
93
        }
94
95
        $dataSet = json_decode($xml, true);
96
        if ($dataSet && (JSON_ERROR_NONE === json_last_error())) {
97
            // For mini-program JSON formats.
98
            // Convert to XML if the given string can be decode into a data array.
99
            $xml = XML::build($dataSet);
100
        }
101
102
        return [ErrorCode::$OK, $xml];
103
    }
104
105
    /**
106
     * 随机生成16位字符串
107
     *
108
     * @return string 生成的字符串
109
     */
110
    public function getRandomStr()
111
    {
112
        $str     = "";
113
        $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
114
        $max     = strlen($str_pol) - 1;
115
        for ($i = 0; $i < 16; $i++) {
116
            $str .= $str_pol[mt_rand(0, $max)];
117
        }
118
119
        return $str;
120
    }
121
122
    /**
123
     * Return AESKey.
124
     *
125
     * @return string
126
     *
127
     * @throws Exception
128
     */
129
    protected function getAESKey()
130
    {
131
        if (empty($this->AESKey)) {
132
            throw new Exception("Configuration mission, 'aes_key' is required.");
133
        }
134
135
        if (strlen($this->AESKey) !== 43) {
136
            throw new Exception("The length of 'aes_key' must be 43.");
137
        }
138
139
        return base64_decode($this->AESKey . '=', true);
140
    }
141
142
    /**
143
     * Decode string.
144
     *
145
     * @param string $decrypted
146
     *
147
     * @return string
148
     */
149 View Code Duplication
    public function decode($decrypted)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
    {
151
        $pad = ord(substr($decrypted, -1));
152
153
        if ($pad < 1 || $pad > $this->blockSize) {
154
            $pad = 0;
155
        }
156
157
        return substr($decrypted, 0, (strlen($decrypted) - $pad));
158
    }
159
160
    /**
161
     * Encode string.
162
     *
163
     * @param string $text
164
     *
165
     * @return string
166
     */
167
    public function encode($text)
168
    {
169
        $padAmount = $this->blockSize - (strlen($text) % $this->blockSize);
170
171
        $padAmount = $padAmount !== 0 ? $padAmount : $this->blockSize;
172
173
        $padChr = chr($padAmount);
174
175
        $tmp = '';
176
177
        for ($index = 0; $index < $padAmount; ++$index) {
178
            $tmp .= $padChr;
179
        }
180
181
        return $text . $tmp;
182
    }
183
184
}
185