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