""" backend/app/services/integrations/wecom/crypto.py 用途:企业微信回调加解密工具(兼容 WXBizMsgCrypt 布局)。 依赖:pycryptodome AES。 逻辑:user/auth 企微回调验签、解密 Encrypt 字段时调用。 """ from __future__ import annotations import base64 import hashlib import random import struct from typing import Optional from Crypto.Cipher import AES def sha1_hex(parts: list[str]) -> str: merged = ''.join(sorted([str(p) for p in parts if p is not None])) return hashlib.sha1(merged.encode('utf-8')).hexdigest() def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes: pad_len = block_size - (len(data) % block_size) return data + bytes([pad_len] * pad_len) def _pkcs7_unpad(data: bytes) -> bytes: if not data: return data pad_len = data[-1] if pad_len < 1 or pad_len > 32: raise ValueError('invalid pkcs7 padding') if data[-pad_len:] != bytes([pad_len] * pad_len): raise ValueError('invalid pkcs7 padding tail') return data[:-pad_len] def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes: raw = (encoding_aes_key_b64 or '').strip() key = base64.b64decode(raw + '=') if len(key) != 32: raise ValueError('EncodingAESKey must decode to 32 bytes') return key def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str: """ Encrypt plain text to base64 ciphertext (for tests / optional outbound use). """ aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64) iv = aes_key[:16] random_bytes = bytes(random.randint(0, 255) for _ in range(16)) msg_bytes = plain_text.encode('utf-8') pack = ( random_bytes + struct.pack('>I', len(msg_bytes)) + msg_bytes + corp_id.encode('utf-8') ) padded = _pkcs7_pad(pack, 32) cipher = AES.new(aes_key, AES.MODE_CBC, iv) encrypted = cipher.encrypt(padded) return base64.b64encode(encrypted).decode('ascii') def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str: aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64) iv = aes_key[:16] cipher_bytes = base64.b64decode(cipher_b64) cipher = AES.new(aes_key, AES.MODE_CBC, iv) plain_padded = cipher.decrypt(cipher_bytes) plain = _pkcs7_unpad(plain_padded) content = plain[16:] if len(content) < 4: raise ValueError('decrypted payload too short') xml_len = struct.unpack('>I', content[:4])[0] xml_bytes = content[4:4 + xml_len] tail = content[4 + xml_len:] if tail.decode('utf-8', errors='strict') != corp_id: raise ValueError('corp_id mismatch after decrypt') return xml_bytes.decode('utf-8') def extract_encrypt_field(xml_body: str) -> Optional[str]: if not xml_body: return None import re m = re.search(r'', xml_body, re.DOTALL) if m: return m.group(1).strip() m2 = re.search(r'(.*?)', xml_body, re.DOTALL) if m2: return m2.group(1).strip() return None