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