Encryptor   A
last analyzed

Complexity

Total Complexity 28

Size/Duplication

Total Lines 294
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 294
rs 10
c 0
b 0
f 0
wmc 28
lcom 1
cbo 4

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
A encryptMsg() 0 20 3
A decryptEcho() 0 6 1
A decryptMsg() 0 18 3
A getSHA1() 0 11 2
A encode() 0 16 3
A decode() 0 10 3
A getAESKey() 0 12 3
A encrypt() 0 16 2
B decrypt() 0 34 5
A getRandomStr() 0 4 1
1
<?php
2
3
namespace YEntWeChat\Encryption;
4
5
use YEntWeChat\Core\Exceptions\InvalidConfigException;
6
use YEntWeChat\Core\Exceptions\RuntimeException;
7
use YEntWeChat\Support\XML;
8
use Exception as BaseException;
9
10
/**
11
 * Class Encryptor.
12
 */
13
class Encryptor
14
{
15
    /**
16
     * ID.
17
     *
18
     * @var string
19
     */
20
    protected $id;
21
22
    /**
23
     * Token.
24
     *
25
     * @var string
26
     */
27
    protected $token;
28
29
    /**
30
     * AES key.
31
     *
32
     * @var string
33
     */
34
    protected $AESKey;
35
36
    /**
37
     * Block size.
38
     *
39
     * @var int
40
     */
41
    protected $blockSize;
42
43
    /**
44
     * Constructor.
45
     *
46
     * @param string $id
47
     * @param string $token
48
     * @param string $AESKey
49
     *
50
     * @throws RuntimeException
51
     */
52
    public function __construct($id, $token, $AESKey)
53
    {
54
        if (!extension_loaded('openssl')) {
55
            throw new RuntimeException("The ext 'openssl' is required.");
56
        }
57
58
        $this->id = $id;
59
        $this->token = $token;
60
        $this->AESKey = $AESKey;
61
        $this->blockSize = 32;
62
    }
63
64
    /**
65
     * Encrypt the message and return XML.
66
     *
67
     * @param string $xml
68
     * @param string $nonce
69
     * @param int    $timestamp
70
     *
71
     * @return string
72
     */
73
    public function encryptMsg($xml, $nonce = null, $timestamp = null)
74
    {
75
        $encrypt = $this->encrypt($xml, $this->id);
76
77
        !is_null($nonce) || $nonce = substr($this->id, 0, 10);
78
        !is_null($timestamp) || $timestamp = time();
79
80
        //生成安全签名
81
        $signature = $this->getSHA1($this->token, $timestamp, $nonce, $encrypt);
82
83
        $response = [
84
            'Encrypt'      => $encrypt,
85
            'MsgSignature' => $signature,
86
            'TimeStamp'    => $timestamp,
87
            'Nonce'        => $nonce,
88
        ];
89
90
        //生成响应xml
91
        return XML::build($response);
92
    }
93
94
    /**
95
     * Decrypt message.
96
     *
97
     * @param string $msgSignature
98
     * @param string $nonce
99
     * @param string $timestamp
100
     * @param string $postXML
0 ignored issues
show
Bug introduced by
There is no parameter named $postXML. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
101
     *
102
     * @throws EncryptionException
103
     *
104
     * @return array
105
     */
106
    public function decryptEcho($msgSignature, $nonce, $timestamp, $echo)
0 ignored issues
show
Unused Code introduced by
The parameter $msgSignature is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $nonce is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $timestamp is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
107
    {
108
        $encrypted = $echo;
109
110
        return $this->decrypt($encrypted, $this->id);
111
    }
112
113
    /**
114
     * Decrypt message.
115
     *
116
     * @param string $msgSignature
117
     * @param string $nonce
118
     * @param string $timestamp
119
     * @param string $postXML
120
     *
121
     * @throws EncryptionException
122
     *
123
     * @return array
124
     */
125
    public function decryptMsg($msgSignature, $nonce, $timestamp, $postXML)
126
    {
127
        try {
128
            $array = XML::parse($postXML);
129
        } catch (BaseException $e) {
130
            throw new EncryptionException('Invalid xml.', EncryptionException::ERROR_PARSE_XML);
131
        }
132
133
        $encrypted = $array['Encrypt'];
134
135
        $signature = $this->getSHA1($this->token, $timestamp, $nonce, $encrypted);
136
137
        if ($signature !== $msgSignature) {
138
            throw new EncryptionException('Invalid Signature.', EncryptionException::ERROR_INVALID_SIGNATURE);
139
        }
140
141
        return XML::parse($this->decrypt($encrypted, $this->id));
142
    }
143
144
    /**
145
     * Get SHA1.
146
     *
147
     * @throws EncryptionException
148
     *
149
     * @return string
150
     */
151
    public function getSHA1()
152
    {
153
        try {
154
            $array = func_get_args();
155
            sort($array, SORT_STRING);
156
157
            return sha1(implode($array));
158
        } catch (BaseException $e) {
159
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_CALC_SIGNATURE);
160
        }
161
    }
162
163
    /**
164
     * Encode string.
165
     *
166
     * @param string $text
167
     *
168
     * @return string
169
     */
170
    public function encode($text)
171
    {
172
        $padAmount = $this->blockSize - (strlen($text) % $this->blockSize);
173
174
        $padAmount = $padAmount !== 0 ? $padAmount : $this->blockSize;
175
176
        $padChr = chr($padAmount);
177
178
        $tmp = '';
179
180
        for ($index = 0; $index < $padAmount; ++$index) {
181
            $tmp .= $padChr;
182
        }
183
184
        return $text.$tmp;
185
    }
186
187
    /**
188
     * Decode string.
189
     *
190
     * @param string $decrypted
191
     *
192
     * @return string
193
     */
194
    public function decode($decrypted)
195
    {
196
        $pad = ord(substr($decrypted, -1));
197
198
        if ($pad < 1 || $pad > $this->blockSize) {
199
            $pad = 0;
200
        }
201
202
        return substr($decrypted, 0, (strlen($decrypted) - $pad));
203
    }
204
205
    /**
206
     * Return AESKey.
207
     *
208
     * @throws InvalidConfigException
209
     *
210
     * @return string
211
     */
212
    protected function getAESKey()
213
    {
214
        if (empty($this->AESKey)) {
215
            throw new InvalidConfigException("Configuration mission, 'aes_key' is required.");
216
        }
217
218
        if (strlen($this->AESKey) !== 43) {
219
            throw new InvalidConfigException("The length of 'aes_key' must be 43.");
220
        }
221
222
        return base64_decode($this->AESKey.'=', true);
223
    }
224
225
    /**
226
     * Encrypt string.
227
     *
228
     * @param string $text
229
     * @param string $corpId
230
     *
231
     * @throws EncryptionException
232
     *
233
     * @return string
234
     */
235
    private function encrypt($text, $corpId)
236
    {
237
        try {
238
            $key = $this->getAESKey();
239
            $random = $this->getRandomStr();
240
            $text = $this->encode($random.pack('N', strlen($text)).$text.$corpId);
241
242
            $iv = substr($key, 0, 16);
243
244
            $encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
245
246
            return base64_encode($encrypted);
247
        } catch (BaseException $e) {
248
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_ENCRYPT_AES);
249
        }
250
    }
251
252
    /**
253
     * Decrypt message.
254
     *
255
     * @param string $encrypted
256
     * @param string $corpId
257
     *
258
     * @throws EncryptionException
259
     *
260
     * @return string
261
     */
262
    private function decrypt($encrypted, $corpId)
263
    {
264
        try {
265
            $key = $this->getAESKey();
266
            $ciphertext = base64_decode($encrypted, true);
267
            $iv = substr($key, 0, 16);
268
269
            $decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
270
        } catch (BaseException $e) {
271
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_DECRYPT_AES);
272
        }
273
274
        try {
275
            $result = $this->decode($decrypted);
276
277
            if (strlen($result) < 16) {
278
                return '';
279
            }
280
281
            $content = substr($result, 16, strlen($result));
282
            $listLen = unpack('N', substr($content, 0, 4));
283
            $xmlLen = $listLen[1];
284
            $xml = substr($content, 4, $xmlLen);
285
            $fromCorpId = trim(substr($content, $xmlLen + 4));
286
        } catch (BaseException $e) {
287
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_INVALID_XML);
288
        }
289
290
        if ($fromCorpId !== $corpId) {
291
            throw new EncryptionException('Invalid corpId.', EncryptionException::ERROR_INVALID_CORPID);
292
        }
293
294
        return $xml;
295
    }
296
297
    /**
298
     * Generate random string.
299
     *
300
     * @return string
301
     */
302
    private function getRandomStr()
303
    {
304
        return substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'), 0, 16);
305
    }
306
}
307