MiniProgramDataCrypt   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 73.68%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 59
ccs 14
cts 19
cp 0.7368
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B decryptData() 0 27 6
1
<?php
2
3
4
namespace Oakhope\OAuth2\Client\Support\MiniProgram;
5
6
/**
7
 * 对微信小程序用户加密数据的解密
8
 *
9
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
10
 */
11
class MiniProgramDataCrypt
12
{
13
    const OK = 0;
14
    const ILLEGAL_AES_KEY = -41001;
15
    const ILLEGAL_IV = -41002;
16
    const ILLEGAL_BUFFER = -41003;
17
    const DECODE_BASE64_ERROR = -41004;
18
19
    private $appid;
20
    private $sessionKey;
21
22
    /**
23
     * 构造函数
24
     * @param $sessionKey string 用户在小程序登录后获取的会话密钥
25
     * @param $appid string 小程序的appid
26
     */
27 6
    public function __construct($appid, $sessionKey)
28
    {
29 6
        $this->sessionKey = $sessionKey;
30 6
        $this->appid = $appid;
31 6
    }
32
33
34
    /**
35
     * 检验数据的真实性,并且获取解密后的明文.
36
     * @param $encryptedData string 加密的用户数据
37
     * @param $iv string 与用户数据一同返回的初始向量
38
     * @param $data string 解密后的原文
39
     *
40
     * @return int 成功0,失败返回对应的错误码
41
     */
42 6
    public function decryptData($encryptedData, $iv, &$data)
43
    {
44 6
        if (strlen($this->sessionKey) != 24) {
45
            return self::ILLEGAL_AES_KEY;
46
        }
47
48 6
        if (strlen($iv) != 24) {
49
            return self::ILLEGAL_IV;
50
        }
51
52 6
        $encoder = new PKCS7Encoder();
53 6
        $result = $encoder->decrypt($encryptedData, $this->sessionKey, $iv);
54
55 6
        if ($result[0] != 0) {
56
            return $result[0];
57
        }
58
59 6
        if ($result[1] == null) {
60
            return self::ILLEGAL_BUFFER;
61
        }
62 6
        if ($result[1]->watermark->appid != $this->appid) {
63
            return self::ILLEGAL_BUFFER;
64
        }
65 6
        $data = $result[1];
66
67 6
        return self::OK;
68
    }
69
}
70