1: <?php
2:
3: 4: 5: 6: 7:
8:
9:
10: include_once "sha1.php";
11: include_once "xmlparse.php";
12: include_once "pkcs7Encoder.php";
13: include_once "errorCode.php";
14:
15: 16: 17: 18:
19: class WXBizMsgCrypt
20: {
21: private $token;
22: private $encodingAesKey;
23: private $appId;
24:
25: 26: 27: 28: 29: 30:
31: public function WXBizMsgCrypt($token, $encodingAesKey, $appId)
32: {
33: $this->token = $token;
34: $this->encodingAesKey = $encodingAesKey;
35: $this->appId = $appId;
36: }
37:
38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53:
54: public function encryptMsg($replyMsg, $timeStamp, $nonce, &$encryptMsg)
55: {
56: $pc = new Prpcrypt($this->encodingAesKey);
57:
58:
59: $array = $pc->encrypt($replyMsg, $this->appId);
60: $ret = $array[0];
61: if ($ret != 0) {
62: return $ret;
63: }
64:
65: if ($timeStamp == null) {
66: $timeStamp = time();
67: }
68: $encrypt = $array[1];
69:
70:
71: $sha1 = new SHA1;
72: $array = $sha1->getSHA1($this->token, $timeStamp, $nonce, $encrypt);
73: $ret = $array[0];
74: if ($ret != 0) {
75: return $ret;
76: }
77: $signature = $array[1];
78:
79:
80: $xmlparse = new XMLParse;
81: $encryptMsg = $xmlparse->generate($encrypt, $signature, $timeStamp, $nonce);
82: return ErrorCode::$OK;
83: }
84:
85:
86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101:
102: public function decryptMsg($msgSignature, $timestamp = null, $nonce, $postData, &$msg)
103: {
104: if (strlen($this->encodingAesKey) != 43) {
105: return ErrorCode::$IllegalAesKey;
106: }
107:
108: $pc = new Prpcrypt($this->encodingAesKey);
109:
110:
111: $xmlparse = new XMLParse;
112: $array = $xmlparse->extract($postData);
113: $ret = $array[0];
114:
115: if ($ret != 0) {
116: return $ret;
117: }
118:
119: if ($timestamp == null) {
120: $timestamp = time();
121: }
122:
123: $encrypt = $array[1];
124: $touser_name = $array[2];
125:
126:
127: $sha1 = new SHA1;
128: $array = $sha1->getSHA1($this->token, $timestamp, $nonce, $encrypt);
129: $ret = $array[0];
130:
131: if ($ret != 0) {
132: return $ret;
133: }
134:
135: $signature = $array[1];
136: if ($signature != $msgSignature) {
137: return ErrorCode::$ValidateSignatureError;
138: }
139:
140: $result = $pc->decrypt($encrypt, $this->appId);
141: if ($result[0] != 0) {
142: return $result[0];
143: }
144: $msg = $result[1];
145:
146: return ErrorCode::$OK;
147: }
148:
149: }
150:
151: