Completed
Push — master ( 7c0e89...5c9864 )
by Wang
13:40
created

MiniProgramDataCrypt::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
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
    public function __construct($appid, $sessionKey)
28
    {
29
        $this->sessionKey = $sessionKey;
30
        $this->appid = $appid;
31
    }
32
33
34
    /**
35
     * 检验数据的真实性,并且获取解密后的明文.
36
     * @param $encryptedData string 加密的用户数据
37
     * @param $iv string 与用户数据一同返回的初始向量
38
     * @param $data string 解密后的原文
39
     *
40
     * @return int 成功0,失败返回对应的错误码
41
     */
42
    public function decryptData($encryptedData, $iv, &$data)
43
    {
44
        if (strlen($this->sessionKey) != 24) {
45
            return self::ILLEGAL_AES_KEY;
46
        }
47
48
        if (strlen($iv) != 24) {
49
            return self::ILLEGAL_IV;
50
        }
51
52
        $encoder = new PKCS7Encoder();
53
        $result = $encoder->decrypt($encryptedData, $this->sessionKey, $iv);
54
55
        if ($result[0] != 0) {
56
            return $result[0];
57
        }
58
59
        if ($result[1] == null) {
60
            return self::ILLEGAL_BUFFER;
61
        }
62
        if ($result[1]->watermark->appid != $this->appid) {
63
            return self::ILLEGAL_BUFFER;
64
        }
65
        $data = $result[1];
66
67
        return self::OK;
68
    }
69
}
70