本次提交包含多项优化与新增功能: 1. 清理多个文件中多余的空行与导入顺序 2. 修复voice.py中的多行字符串格式化问题 3. 新增微信公众号被动回复构建函数与配置项 4. 新增企业微信markdown消息发送支持 5. 新增消息去重TTL与最大条目配置 6. 新增markdown文本截断工具函数 7. 新增微信授权与OAuth相关工具方法 8. 重构消息去重逻辑,使用DedupPolicy替代本地字典实现 9. 新增子账号多租户支持功能 10. 新增消息动作处理适配器,支持send/reply等操作 11. 修复token持久化逻辑,新增状态存储支持
70 lines
2.1 KiB
Python
70 lines
2.1 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import os
|
|
import socket
|
|
import struct
|
|
|
|
from cryptography.hazmat.primitives import padding as sym_padding
|
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
|
|
|
|
def verify_signature(token: str, timestamp: str, nonce: str, signature: str) -> bool:
|
|
params = sorted([token, timestamp, nonce])
|
|
sha1 = hashlib.sha1("".join(params).encode()).hexdigest()
|
|
return sha1 == signature
|
|
|
|
|
|
def decrypt_message(
|
|
encrypted_msg: str,
|
|
encoding_aes_key: str,
|
|
) -> tuple[str, str]:
|
|
key = base64.b64decode(encoding_aes_key + "=")
|
|
ciphertext = base64.b64decode(encrypted_msg)
|
|
|
|
cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]))
|
|
decryptor = cipher.decryptor()
|
|
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
|
|
|
|
pad = plaintext[-1]
|
|
plaintext = plaintext[:-pad]
|
|
|
|
content_len = socket.ntohl(struct.unpack("I", plaintext[16:20])[0])
|
|
content = plaintext[20 : 20 + content_len].decode("utf-8")
|
|
receive_id = plaintext[20 + content_len :].decode("utf-8")
|
|
|
|
return content, receive_id
|
|
|
|
|
|
def encrypt_message(
|
|
content: str,
|
|
encoding_aes_key: str,
|
|
app_id: str,
|
|
) -> str:
|
|
key = base64.b64decode(encoding_aes_key + "=")
|
|
|
|
random_bytes = os.urandom(16)
|
|
content_bytes = content.encode("utf-8")
|
|
app_id_bytes = app_id.encode("utf-8")
|
|
|
|
msg_len = struct.pack("!I", len(content_bytes))
|
|
raw = random_bytes + msg_len + content_bytes + app_id_bytes
|
|
|
|
padder = sym_padding.PKCS7(128).padder()
|
|
padded = padder.update(raw) + padder.finalize()
|
|
|
|
cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]))
|
|
encryptor = cipher.encryptor()
|
|
ciphertext = encryptor.update(padded) + encryptor.finalize()
|
|
|
|
return base64.b64encode(ciphertext).decode()
|
|
|
|
|
|
def verify_url_signature(token: str, timestamp: str, nonce: str, echostr: str, signature: str) -> tuple[bool, str]:
|
|
if not verify_signature(token, timestamp, nonce, signature):
|
|
return False, ""
|
|
|
|
key = base64.b64decode(echostr)
|
|
return True, key.decode("utf-8")
|