def get_reply(self, message): """ 根据 message 的内容获取 Reply 对象。 :param message: 要处理的 message :return: 获取的 Reply 对象 """ session_storage = self.session_storage id = None session = None if session_storage and hasattr(message, "source"): id = to_binary(message.source) session = session_storage[id] handlers = self.get_handlers(message.type) try: for handler, args_count in handlers: args = [message, session][:args_count] reply = handler(*args) if session_storage and id: session_storage[id] = session if reply: return process_function_reply(reply, message=message) except: self.logger.exception("Catch an exception")
def __init__(self, token, encoding_aes_key, corp_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.corp_id = corp_id
def encrypt(self, text, corp_id): """ 对明文进行加密 :param text: 需要加密的明文 :param corp_id: 微信公众平台的 AppID :return: 加密后的字符串 """ text = b"".join([ to_binary(self.get_random_string()), struct.pack(b"I", socket.htonl(len(to_binary(text)))), to_binary(text), to_binary(corp_id) ]) text = pkcs7.encode(text) encryptor = self.cipher.encryptor() ciphertext = to_binary(encryptor.update(text) + encryptor.finalize()) return base64.b64encode(ciphertext)
def encode(text): # 计算需要填充的位数 amount_to_pad = _BLOCK_SIZE - (len(text) % _BLOCK_SIZE) if not amount_to_pad: amount_to_pad = _BLOCK_SIZE # 获得补位所用的字符 pad = chr(amount_to_pad) return text + to_binary(pad * amount_to_pad)
def decrypt(self, text, corp_id): """ 对密文进行解密 :param text: 需要解密的密文 :param corp_id: 微信公众平台的 AppID :return: 解密后的字符串 """ text = to_binary(text) decryptor = self.cipher.decryptor() plain_text = decryptor.update( base64.b64decode(text)) + decryptor.finalize() 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) != corp_id: raise AppIdValidationError(text, corp_id) return xml_content
def __init__(self, key): key = to_binary(key) self.cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]), backend=default_backend())
def __init__(self, filename='werobot_session'): try: self.db = dbm.open(filename, "c") except TypeError: # pragma: no cover # dbm in PyPy requires filename to be binary self.db = dbm.open(to_binary(filename), "c")