wx-crypt 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ .idea
2
+ dist
3
+ .DS_Store
4
+ *.pyc
5
+ __pycache__
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: wx-crypt
3
+ Version: 0.0.1
4
+ Summary: WeCom Bot Callback Server Simple Framework
5
+ Project-URL: Homepage, https://github.com/easy-wx/wx-crypt
6
+ Project-URL: Issues, https://github.com/easy-wx/wx-crypt/issues
7
+ Author-email: panzhongxian <panzhongxian0532@gmail.com>
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Requires-Dist: pycryptodome>=3.10.0
File without changes
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+
6
+ [project]
7
+ name = "wx-crypt"
8
+ version = "0.0.1"
9
+ authors = [
10
+ { name = "panzhongxian", email = "panzhongxian0532@gmail.com" },
11
+ ]
12
+ description = "WeCom Bot Callback Server Simple Framework"
13
+ readme = "README.md"
14
+ requires-python = ">=3.8"
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+ dependencies = [
21
+ "pycryptodome>=3.10.0",
22
+ ]
23
+ [project.urls]
24
+ Homepage = "https://github.com/easy-wx/wx-crypt"
25
+ Issues = "https://github.com/easy-wx/wx-crypt/issues"
@@ -0,0 +1,292 @@
1
+ #!/usr/bin/env python
2
+ # -*- encoding:utf-8 -*-
3
+ """ 对企业微信发送给企业后台的消息加解密示例代码.
4
+ @copyright: Copyright (c) 1998-2014 Tencent Inc.
5
+ """
6
+ # ------------------------------------------------------------------------
7
+ import logging
8
+ import base64
9
+ import random
10
+ import hashlib
11
+ import time
12
+ import struct
13
+ from Crypto.Cipher import AES
14
+ import xml.etree.cElementTree as ET
15
+ import socket
16
+
17
+ import wx_crypt.ierror
18
+ from wx_crypt.channel import WxChannel_Mp, WxChannel_Wecom
19
+ """
20
+ 关于Crypto.Cipher模块,ImportError: No module named 'Crypto'解决方案
21
+ 请到官方网站 https://www.dlitz.net/software/pycrypto/ 下载pycrypto。
22
+ 下载后,按照README中的“Installation”小节的提示进行pycrypto安装。
23
+ """
24
+
25
+
26
+ class FormatException(Exception):
27
+ pass
28
+
29
+
30
+ def throw_exception(message, exception_class=FormatException):
31
+ """my define raise exception function"""
32
+ raise exception_class(message)
33
+
34
+
35
+ class SHA1:
36
+ """计算企业微信的消息签名接口"""
37
+
38
+ def getSHA1(self, token, timestamp, nonce, encrypt):
39
+ """用SHA1算法生成安全签名
40
+ @param token: 票据
41
+ @param timestamp: 时间戳
42
+ @param encrypt: 密文
43
+ @param nonce: 随机字符串
44
+ @return: 安全签名
45
+ """
46
+ try:
47
+ sortlist = [token, timestamp, nonce, encrypt]
48
+ sortlist.sort()
49
+ sha = hashlib.sha1()
50
+ sha.update("".join(sortlist).encode())
51
+ return ierror.WXBizMsgCrypt_OK, sha.hexdigest()
52
+ except Exception as e:
53
+ logger = logging.getLogger()
54
+ logger.error(e)
55
+ return ierror.WXBizMsgCrypt_ComputeSignature_Error, None
56
+
57
+
58
+ class XMLParse:
59
+ """提供提取消息格式中的密文及生成回复消息格式的接口"""
60
+
61
+ # xml消息模板
62
+ AES_TEXT_RESPONSE_TEMPLATE = """<xml>
63
+ <Encrypt><![CDATA[%(msg_encrypt)s]]></Encrypt>
64
+ <MsgSignature><![CDATA[%(msg_signaturet)s]]></MsgSignature>
65
+ <TimeStamp>%(timestamp)s</TimeStamp>
66
+ <Nonce><![CDATA[%(nonce)s]]></Nonce>
67
+ </xml>"""
68
+
69
+ def extract(self, xmltext):
70
+ """提取出xml数据包中的加密消息
71
+ @param xmltext: 待提取的xml字符串
72
+ @return: 提取出的加密消息字符串
73
+ """
74
+ try:
75
+ xml_tree = ET.fromstring(xmltext)
76
+ encrypt = xml_tree.find("Encrypt")
77
+ return ierror.WXBizMsgCrypt_OK, encrypt.text
78
+ except Exception as e:
79
+ logger = logging.getLogger()
80
+ logger.error(e)
81
+ return ierror.WXBizMsgCrypt_ParseXml_Error, None
82
+
83
+ def generate(self, encrypt, signature, timestamp, nonce):
84
+ """生成xml消息
85
+ @param encrypt: 加密后的消息密文
86
+ @param signature: 安全签名
87
+ @param timestamp: 时间戳
88
+ @param nonce: 随机字符串
89
+ @return: 生成的xml字符串
90
+ """
91
+ resp_dict = {
92
+ 'msg_encrypt': encrypt,
93
+ 'msg_signaturet': signature,
94
+ 'timestamp': timestamp,
95
+ 'nonce': nonce,
96
+ }
97
+ resp_xml = self.AES_TEXT_RESPONSE_TEMPLATE % resp_dict
98
+ return resp_xml
99
+
100
+
101
+ class PKCS7Encoder():
102
+ """提供基于PKCS7算法的加解密接口"""
103
+
104
+ block_size = 32
105
+
106
+ def encode(self, text):
107
+ """ 对需要加密的明文进行填充补位
108
+ @param text: 需要进行填充补位操作的明文
109
+ @return: 补齐明文字符串
110
+ """
111
+ text_length = len(text)
112
+ # 计算需要填充的位数
113
+ amount_to_pad = self.block_size - (text_length % self.block_size)
114
+ if amount_to_pad == 0:
115
+ amount_to_pad = self.block_size
116
+ # 获得补位所用的字符
117
+ pad = chr(amount_to_pad)
118
+ return text + (pad * amount_to_pad).encode()
119
+
120
+ def decode(self, decrypted):
121
+ """删除解密后明文的补位字符
122
+ @param decrypted: 解密后的明文
123
+ @return: 删除补位字符后的明文
124
+ """
125
+ pad = ord(decrypted[-1])
126
+ if pad < 1 or pad > 32:
127
+ pad = 0
128
+ return decrypted[:-pad]
129
+
130
+
131
+ class Prpcrypt(object):
132
+ """提供接收和推送给企业微信消息的加解密接口"""
133
+
134
+ def __init__(self, key):
135
+
136
+ # self.key = base64.b64decode(key+"=")
137
+ self.key = key
138
+ # 设置加解密模式为AES的CBC模式
139
+ self.mode = AES.MODE_CBC
140
+
141
+ def encrypt(self, text, receiveid):
142
+ """对明文进行加密
143
+ @param text: 需要加密的明文
144
+ @return: 加密得到的字符串
145
+ """
146
+ # 16位随机字符串添加到明文开头
147
+ if text is bytes:
148
+ text = text.encode()
149
+ text = self.get_random_str() + struct.pack("I", socket.htonl(
150
+ len(text))) + text + receiveid.encode()
151
+
152
+ # 使用自定义的填充方式对明文进行补位填充
153
+ pkcs7 = PKCS7Encoder()
154
+ text = pkcs7.encode(text)
155
+ # 加密
156
+ cryptor = AES.new(self.key, self.mode, self.key[:16])
157
+ try:
158
+ ciphertext = cryptor.encrypt(text)
159
+ # 使用BASE64对加密后的字符串进行编码
160
+ return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
161
+ except Exception as e:
162
+ logger = logging.getLogger()
163
+ logger.error(e)
164
+ return ierror.WXBizMsgCrypt_EncryptAES_Error, None
165
+
166
+ def decrypt(self, text, receiveid):
167
+ """对解密后的明文进行补位删除
168
+ @param text: 密文
169
+ @return: 删除填充补位后的明文
170
+ """
171
+ try:
172
+ cryptor = AES.new(self.key, self.mode, self.key[:16])
173
+ # 使用BASE64对密文进行解码,然后AES-CBC解密
174
+ plain_text = cryptor.decrypt(base64.b64decode(text))
175
+ except Exception as e:
176
+ logger = logging.getLogger()
177
+ logger.error(e)
178
+ return ierror.WXBizMsgCrypt_DecryptAES_Error, None
179
+ try:
180
+ pad = plain_text[-1]
181
+ # 去掉补位字符串
182
+ # pkcs7 = PKCS7Encoder()
183
+ # plain_text = pkcs7.encode(plain_text)
184
+ # 去除16位随机字符串
185
+ content = plain_text[16:-pad]
186
+ xml_len = socket.ntohl(struct.unpack("I", content[:4])[0])
187
+ xml_content = content[4:xml_len + 4]
188
+ from_receiveid = content[xml_len + 4:]
189
+ except Exception as e:
190
+ logger = logging.getLogger()
191
+ logger.error(e)
192
+ return ierror.WXBizMsgCrypt_IllegalBuffer, None
193
+
194
+ if from_receiveid.decode('utf8') != receiveid:
195
+ return ierror.WXBizMsgCrypt_ValidateCorpid_Error, None
196
+ return 0, xml_content
197
+
198
+ def get_random_str(self):
199
+ """ 随机生成16位字符串
200
+ @return: 16位字符串
201
+ """
202
+ return str(random.randint(1000000000000000, 9999999999999999)).encode()
203
+
204
+
205
+ class WXBizMsgCrypt(object):
206
+ # 构造函数
207
+ def __init__(self,
208
+ sToken,
209
+ sEncodingAESKey,
210
+ sReceiveId,
211
+ channel=WxChannel_Wecom):
212
+ self.channel = channel
213
+ try:
214
+ self.key = base64.b64decode(sEncodingAESKey + "=")
215
+ assert len(self.key) == 32
216
+ except:
217
+ throw_exception("[error]: EncodingAESKey unvalid !",
218
+ FormatException)
219
+ # return ierror.WXBizMsgCrypt_IllegalAesKey,None
220
+ self.m_sToken = sToken
221
+ self.m_sReceiveId = sReceiveId
222
+
223
+ # 验证URL
224
+ # @param sMsgSignature: 签名串,对应URL参数的msg_signature
225
+ # @param sTimeStamp: 时间戳,对应URL参数的timestamp
226
+ # @param sNonce: 随机串,对应URL参数的nonce
227
+ # @param sEchoStr: 随机串,对应URL参数的echostr
228
+ # @param sReplyEchoStr: 解密之后的echostr,当return返回0时有效
229
+ # @return:成功0,失败返回对应的错误码
230
+
231
+ def VerifyURL(self, sMsgSignature, sTimeStamp, sNonce, sEchoStr):
232
+ sha1 = SHA1()
233
+ ret, signature = sha1.getSHA1(
234
+ self.m_sToken, sTimeStamp, sNonce,
235
+ "" if self.channel == WxChannel_Mp else sEchoStr)
236
+ if ret != 0:
237
+ return ret, None
238
+ if not signature == sMsgSignature:
239
+ return ierror.WXBizMsgCrypt_ValidateSignature_Error, None
240
+
241
+ if self.channel == WxChannel_Mp:
242
+ return 0, sEchoStr
243
+ pc = Prpcrypt(self.key)
244
+ ret, sReplyEchoStr = pc.decrypt(sEchoStr, self.m_sReceiveId)
245
+ return ret, sReplyEchoStr
246
+
247
+ def EncryptMsg(self, sReplyMsg, sNonce, timestamp=None):
248
+ # 将企业回复用户的消息加密打包
249
+ # @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串
250
+ # @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp,如为None则自动用当前时间
251
+ # @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
252
+ # sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
253
+ # return:成功0,sEncryptMsg,失败返回对应的错误码None
254
+ pc = Prpcrypt(self.key)
255
+ ret, encrypt = pc.encrypt(sReplyMsg, self.m_sReceiveId)
256
+ encrypt = encrypt.decode('utf8')
257
+ if ret != 0:
258
+ return ret, None
259
+ if timestamp is None:
260
+ timestamp = str(int(time.time()))
261
+ # 生成安全签名
262
+ sha1 = SHA1()
263
+ ret, signature = sha1.getSHA1(self.m_sToken, timestamp, sNonce, encrypt)
264
+ if ret != 0:
265
+ return ret, None
266
+ xmlParse = XMLParse()
267
+ return ret, xmlParse.generate(encrypt, signature, timestamp, sNonce)
268
+
269
+ def DecryptMsg(self, sPostData, sMsgSignature, sTimeStamp, sNonce):
270
+ # 检验消息的真实性,并且获取解密后的明文
271
+ # @param sMsgSignature: 签名串,对应URL参数的msg_signature
272
+ # @param sTimeStamp: 时间戳,对应URL参数的timestamp
273
+ # @param sNonce: 随机串,对应URL参数的nonce
274
+ # @param sPostData: 密文,对应POST请求的数据
275
+ # xml_content: 解密后的原文,当return返回0时有效
276
+ # @return: 成功0,失败返回对应的错误码
277
+ # 验证安全签名
278
+ xmlParse = XMLParse()
279
+ ret, encrypt = xmlParse.extract(sPostData)
280
+ if ret != 0:
281
+ return ret, None
282
+ sha1 = SHA1()
283
+ ret, signature = sha1.getSHA1(
284
+ self.m_sToken, sTimeStamp, sNonce,
285
+ "" if self.channel == WxChannel_Mp else encrypt)
286
+ if ret != 0:
287
+ return ret, None
288
+ if not signature == sMsgSignature:
289
+ return ierror.WXBizMsgCrypt_ValidateSignature_Error, None
290
+ pc = Prpcrypt(self.key)
291
+ ret, xml_content = pc.decrypt(encrypt, self.m_sReceiveId)
292
+ return ret, xml_content
@@ -0,0 +1,8 @@
1
+ from wx_crypt.ierror import *
2
+ from wx_crypt.WXBizMsgCrypt3 import WXBizMsgCrypt
3
+ # 平台相关
4
+ from wx_crypt.WXBizMsgCrypt3 import WxChannel_Wecom, WxChannel_Mp
5
+
6
+ __author__ = "Pan Zhongxian(panzhongxian0532@gmail.com)"
7
+
8
+ __all__ = ["WXBizMsgCrypt", "WxChannel_Wecom", "WxChannel_Mp", "ierror"]
@@ -0,0 +1,2 @@
1
+ WxChannel_Wecom = 1 # 企业微信
2
+ WxChannel_Mp = 2 # 公众号
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ #########################################################################
4
+ # Author: jonyqin
5
+ # Created Time: Thu 11 Sep 2014 01:53:58 PM CST
6
+ # File Name: ierror.py
7
+ # Description:定义错误码含义
8
+ #########################################################################
9
+ WXBizMsgCrypt_OK = 0
10
+ WXBizMsgCrypt_ValidateSignature_Error = -40001
11
+ WXBizMsgCrypt_ParseXml_Error = -40002
12
+ WXBizMsgCrypt_ComputeSignature_Error = -40003
13
+ WXBizMsgCrypt_IllegalAesKey = -40004
14
+ WXBizMsgCrypt_ValidateCorpid_Error = -40005
15
+ WXBizMsgCrypt_EncryptAES_Error = -40006
16
+ WXBizMsgCrypt_DecryptAES_Error = -40007
17
+ WXBizMsgCrypt_IllegalBuffer = -40008
18
+ WXBizMsgCrypt_EncodeBase64_Error = -40009
19
+ WXBizMsgCrypt_DecodeBase64_Error = -40010
20
+ WXBizMsgCrypt_GenReturnXml_Error = -40011