WXBizMsgCrypt3.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. import ierror
  17. """
  18. 关于Crypto.Cipher模块,ImportError: No module named 'Crypto'解决方案
  19. 请到官方网站 https://www.dlitz.net/software/pycrypto/ 下载pycrypto。
  20. 下载后,按照README中的“Installation”小节的提示进行pycrypto安装。
  21. """
  22. class FormatException(Exception):
  23. pass
  24. def throw_exception(message, exception_class=FormatException):
  25. """my define raise exception function"""
  26. raise exception_class(message)
  27. class SHA1:
  28. """计算企业微信的消息签名接口"""
  29. def getSHA1(self, token, timestamp, nonce, encrypt):
  30. """用SHA1算法生成安全签名
  31. @param token: 票据
  32. @param timestamp: 时间戳
  33. @param encrypt: 密文
  34. @param nonce: 随机字符串
  35. @return: 安全签名
  36. """
  37. try:
  38. sortlist = [token, timestamp, nonce, encrypt]
  39. sortlist.sort()
  40. sha = hashlib.sha1()
  41. sha.update("".join(sortlist).encode())
  42. return ierror.WXBizMsgCrypt_OK, sha.hexdigest()
  43. except Exception as e:
  44. logger = logging.getLogger()
  45. logger.error(e)
  46. return ierror.WXBizMsgCrypt_ComputeSignature_Error, None
  47. class XMLParse:
  48. """提供提取消息格式中的密文及生成回复消息格式的接口"""
  49. # xml消息模板
  50. AES_TEXT_RESPONSE_TEMPLATE = """<xml>
  51. <Encrypt><![CDATA[%(msg_encrypt)s]]></Encrypt>
  52. <MsgSignature><![CDATA[%(msg_signaturet)s]]></MsgSignature>
  53. <TimeStamp>%(timestamp)s</TimeStamp>
  54. <Nonce><![CDATA[%(nonce)s]]></Nonce>
  55. </xml>"""
  56. def extract(self, xmltext):
  57. """提取出xml数据包中的加密消息
  58. @param xmltext: 待提取的xml字符串
  59. @return: 提取出的加密消息字符串
  60. """
  61. try:
  62. xml_tree = ET.fromstring(xmltext)
  63. encrypt = xml_tree.find("Encrypt")
  64. return ierror.WXBizMsgCrypt_OK, encrypt.text
  65. except Exception as e:
  66. logger = logging.getLogger()
  67. logger.error(e)
  68. return ierror.WXBizMsgCrypt_ParseXml_Error, None
  69. def generate(self, encrypt, signature, timestamp, nonce):
  70. """生成xml消息
  71. @param encrypt: 加密后的消息密文
  72. @param signature: 安全签名
  73. @param timestamp: 时间戳
  74. @param nonce: 随机字符串
  75. @return: 生成的xml字符串
  76. """
  77. resp_dict = {
  78. 'msg_encrypt': encrypt,
  79. 'msg_signaturet': signature,
  80. 'timestamp': timestamp,
  81. 'nonce': nonce,
  82. }
  83. resp_xml = self.AES_TEXT_RESPONSE_TEMPLATE % resp_dict
  84. return resp_xml
  85. class PKCS7Encoder():
  86. """提供基于PKCS7算法的加解密接口"""
  87. block_size = 32
  88. def encode(self, text):
  89. """ 对需要加密的明文进行填充补位
  90. @param text: 需要进行填充补位操作的明文
  91. @return: 补齐明文字符串
  92. """
  93. text_length = len(text)
  94. # 计算需要填充的位数
  95. amount_to_pad = self.block_size - (text_length % self.block_size)
  96. if amount_to_pad == 0:
  97. amount_to_pad = self.block_size
  98. # 获得补位所用的字符
  99. pad = chr(amount_to_pad)
  100. return text + (pad * amount_to_pad).encode()
  101. def decode(self, decrypted):
  102. """删除解密后明文的补位字符
  103. @param decrypted: 解密后的明文
  104. @return: 删除补位字符后的明文
  105. """
  106. pad = ord(decrypted[-1])
  107. if pad < 1 or pad > 32:
  108. pad = 0
  109. return decrypted[:-pad]
  110. class Prpcrypt(object):
  111. """提供接收和推送给企业微信消息的加解密接口"""
  112. def __init__(self, key):
  113. # self.key = base64.b64decode(key+"=")
  114. self.key = key
  115. # 设置加解密模式为AES的CBC模式
  116. self.mode = AES.MODE_CBC
  117. def encrypt(self, text, receiveid):
  118. """对明文进行加密
  119. @param text: 需要加密的明文
  120. @return: 加密得到的字符串
  121. """
  122. # 16位随机字符串添加到明文开头
  123. text = text.encode()
  124. text = self.get_random_str() + struct.pack("I", socket.htonl(len(text))) + text + receiveid.encode()
  125. # 使用自定义的填充方式对明文进行补位填充
  126. pkcs7 = PKCS7Encoder()
  127. text = pkcs7.encode(text)
  128. # 加密
  129. cryptor = AES.new(self.key, self.mode, self.key[:16])
  130. try:
  131. ciphertext = cryptor.encrypt(text)
  132. # 使用BASE64对加密后的字符串进行编码
  133. return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
  134. except Exception as e:
  135. logger = logging.getLogger()
  136. logger.error(e)
  137. return ierror.WXBizMsgCrypt_EncryptAES_Error, None
  138. def decrypt(self, text, receiveid):
  139. """对解密后的明文进行补位删除
  140. @param text: 密文
  141. @return: 删除填充补位后的明文
  142. """
  143. try:
  144. cryptor = AES.new(self.key, self.mode, self.key[:16])
  145. # 使用BASE64对密文进行解码,然后AES-CBC解密
  146. plain_text = cryptor.decrypt(base64.b64decode(text))
  147. except Exception as e:
  148. logger = logging.getLogger()
  149. logger.error(e)
  150. return ierror.WXBizMsgCrypt_DecryptAES_Error, None
  151. try:
  152. pad = plain_text[-1]
  153. # 去掉补位字符串
  154. # pkcs7 = PKCS7Encoder()
  155. # plain_text = pkcs7.encode(plain_text)
  156. # 去除16位随机字符串
  157. content = plain_text[16:-pad]
  158. xml_len = socket.ntohl(struct.unpack("I", content[: 4])[0])
  159. xml_content = content[4: xml_len + 4]
  160. from_receiveid = content[xml_len + 4:]
  161. except Exception as e:
  162. logger = logging.getLogger()
  163. logger.error(e)
  164. return ierror.WXBizMsgCrypt_IllegalBuffer, None
  165. if from_receiveid.decode('utf8') != receiveid:
  166. return ierror.WXBizMsgCrypt_ValidateCorpid_Error, None
  167. return 0, xml_content
  168. def get_random_str(self):
  169. """ 随机生成16位字符串
  170. @return: 16位字符串
  171. """
  172. return str(random.randint(1000000000000000, 9999999999999999)).encode()
  173. class WXBizMsgCrypt(object):
  174. # 构造函数
  175. def __init__(self, sToken, sEncodingAESKey, sReceiveId):
  176. try:
  177. self.key = base64.b64decode(sEncodingAESKey + "=")
  178. assert len(self.key) == 32
  179. except:
  180. throw_exception("[error]: EncodingAESKey unvalid !", FormatException)
  181. # return ierror.WXBizMsgCrypt_IllegalAesKey,None
  182. self.m_sToken = sToken
  183. self.m_sReceiveId = sReceiveId
  184. # 验证URL
  185. # @param sMsgSignature: 签名串,对应URL参数的msg_signature
  186. # @param sTimeStamp: 时间戳,对应URL参数的timestamp
  187. # @param sNonce: 随机串,对应URL参数的nonce
  188. # @param sEchoStr: 随机串,对应URL参数的echostr
  189. # @param sReplyEchoStr: 解密之后的echostr,当return返回0时有效
  190. # @return:成功0,失败返回对应的错误码
  191. def VerifyURL(self, sMsgSignature, sTimeStamp, sNonce, sEchoStr):
  192. sha1 = SHA1()
  193. ret, signature = sha1.getSHA1(self.m_sToken, sTimeStamp, sNonce, sEchoStr)
  194. if ret != 0:
  195. return ret, None
  196. if not signature == sMsgSignature:
  197. return ierror.WXBizMsgCrypt_ValidateSignature_Error, None
  198. pc = Prpcrypt(self.key)
  199. ret, sReplyEchoStr = pc.decrypt(sEchoStr, self.m_sReceiveId)
  200. return ret, sReplyEchoStr
  201. def EncryptMsg(self, sReplyMsg, sNonce, timestamp=None):
  202. # 将企业回复用户的消息加密打包
  203. # @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串
  204. # @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp,如为None则自动用当前时间
  205. # @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
  206. # sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
  207. # return:成功0,sEncryptMsg,失败返回对应的错误码None
  208. pc = Prpcrypt(self.key)
  209. ret, encrypt = pc.encrypt(sReplyMsg, self.m_sReceiveId)
  210. encrypt = encrypt.decode('utf8')
  211. if ret != 0:
  212. return ret, None
  213. if timestamp is None:
  214. timestamp = str(int(time.time()))
  215. # 生成安全签名
  216. sha1 = SHA1()
  217. ret, signature = sha1.getSHA1(self.m_sToken, timestamp, sNonce, encrypt)
  218. if ret != 0:
  219. return ret, None
  220. xmlParse = XMLParse()
  221. return ret, xmlParse.generate(encrypt, signature, timestamp, sNonce)
  222. def DecryptMsg(self, sPostData, sMsgSignature, sTimeStamp, sNonce):
  223. # 检验消息的真实性,并且获取解密后的明文
  224. # @param sMsgSignature: 签名串,对应URL参数的msg_signature
  225. # @param sTimeStamp: 时间戳,对应URL参数的timestamp
  226. # @param sNonce: 随机串,对应URL参数的nonce
  227. # @param sPostData: 密文,对应POST请求的数据
  228. # xml_content: 解密后的原文,当return返回0时有效
  229. # @return: 成功0,失败返回对应的错误码
  230. # 验证安全签名
  231. xmlParse = XMLParse()
  232. ret, encrypt = xmlParse.extract(sPostData)
  233. if ret != 0:
  234. return ret, None
  235. sha1 = SHA1()
  236. ret, signature = sha1.getSHA1(self.m_sToken, sTimeStamp, sNonce, encrypt)
  237. if ret != 0:
  238. return ret, None
  239. if not signature == sMsgSignature:
  240. return ierror.WXBizMsgCrypt_ValidateSignature_Error, None
  241. pc = Prpcrypt(self.key)
  242. ret, xml_content = pc.decrypt(encrypt, self.m_sReceiveId)
  243. return ret, xml_content