def __init__(self, token, encoding_aes_key, app_id): key = base64.b64decode(to_binary(encoding_aes_key + '=')) if len(key) != 32: raise UnvalidEncodingAESKey(encoding_aes_key) self.prp_crypto = PrpCrypto(key) self.token = token self.app_id = app_id
def encrypt(self, text, app_id): """ 对明文进行加密 :param text: 需要加密的明文 :param app_id: 微信公众平台的 AppID :return: 加密后的字符串 """ text = b"".join([ self.get_random_string(), struct.pack(b"I", socket.htonl(len(text))), to_binary(text), to_binary(app_id) ]) text = pkcs7.encode(text) ciphertext = to_binary(self.cipher.encrypt(text)) return base64.b64encode(ciphertext)
def encrypt_message(self, reply, timestamp=None, nonce=None): """ 加密微信回复 :param reply: 加密前的回复 :type reply: WeChatReply 或 XML 文本 :return: 加密后的回复文本 """ if hasattr(reply, "render"): reply = reply.render() timestamp = timestamp or to_binary(int(time.time())) nonce = nonce or generate_token(5) encrypt = to_text(self.prp_crypto.encrypt(reply, self.app_id)) signature = get_signature(self.token, timestamp, nonce, encrypt) return to_text(self.ENCRYPTED_MESSAGE_XML.format( encrypt=encrypt, signature=signature, timestamp=timestamp, nonce=nonce ))
def decrypt(self, text, app_id): """ 对密文进行解密 :param text: 需要解密的密文 :param app_id: 微信公众平台的 AppID :return: 解密后的字符串 """ text = to_binary(text) plain_text = self.cipher.decrypt(base64.b64decode(text)) padding = byte2int(plain_text, -1) content = plain_text[16:-padding] xml_len = socket.ntohl(struct.unpack("I", content[:4])[0]) xml_content = content[4:xml_len+4] from_appid = content[xml_len+4:] if to_text(from_appid) != app_id: raise AppIdValidationError(text, app_id) return xml_content