wecom_crypto.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. """WeCom callback-mode AES-CBC crypto, wire-compatible with Tencent's official ``WXBizMsgCrypt`` SDK."""
  2. from __future__ import annotations
  3. import base64
  4. import hashlib
  5. import os
  6. import secrets
  7. import socket
  8. import struct
  9. from typing import Optional
  10. from xml.etree import ElementTree as ET
  11. from cryptography.hazmat.backends import default_backend
  12. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  13. class WeComCryptoError(Exception):
  14. pass
  15. class SignatureError(WeComCryptoError): pass
  16. class DecryptError(WeComCryptoError): pass
  17. class EncryptError(WeComCryptoError): pass
  18. class PKCS7Encoder:
  19. block_size = 32
  20. @classmethod
  21. def encode(cls, text: bytes) -> bytes:
  22. amount_to_pad = cls.block_size - (len(text) % cls.block_size) or cls.block_size
  23. return text + bytes([amount_to_pad]) * amount_to_pad
  24. @classmethod
  25. def decode(cls, decrypted: bytes) -> bytes:
  26. if not decrypted:
  27. raise DecryptError("empty decrypted payload")
  28. pad = decrypted[-1]
  29. if pad < 1 or pad > cls.block_size:
  30. raise DecryptError("invalid PKCS7 padding")
  31. if decrypted[-pad:] != bytes([pad]) * pad:
  32. raise DecryptError("malformed PKCS7 padding")
  33. return decrypted[:-pad]
  34. def _sha1_signature(token: str, timestamp: str, nonce: str, encrypt: str) -> str:
  35. return hashlib.sha1("".join(sorted([token, timestamp, nonce, encrypt])).encode("utf-8")).hexdigest()
  36. class WXBizMsgCrypt:
  37. """Minimal WeCom callback crypto helper compatible with BizMsgCrypt semantics."""
  38. def __init__(self, token: str, encoding_aes_key: str, receive_id: str):
  39. for bad, message in (
  40. (not token, "token is required"), (not encoding_aes_key, "encoding_aes_key is required"),
  41. (len(encoding_aes_key) != 43, "encoding_aes_key must be 43 chars"), (not receive_id, "receive_id is required"),
  42. ):
  43. if bad:
  44. raise ValueError(message)
  45. self.token, self.receive_id = token, receive_id
  46. self.key = base64.b64decode(encoding_aes_key + "=")
  47. self.iv = self.key[:16]
  48. def _cipher(self) -> Cipher:
  49. return Cipher(algorithms.AES(self.key), modes.CBC(self.iv), backend=default_backend())
  50. def verify_url(self, msg_signature: str, timestamp: str, nonce: str, echostr: str) -> str:
  51. return self.decrypt(msg_signature, timestamp, nonce, echostr).decode("utf-8")
  52. def decrypt(self, msg_signature: str, timestamp: str, nonce: str, encrypt: str) -> bytes:
  53. if _sha1_signature(self.token, timestamp, nonce, encrypt) != msg_signature:
  54. raise SignatureError("signature mismatch")
  55. try:
  56. cipher_text = base64.b64decode(encrypt)
  57. except Exception as exc:
  58. raise DecryptError(f"invalid base64 payload: {exc}") from exc
  59. try:
  60. decryptor = self._cipher().decryptor()
  61. content = PKCS7Encoder.decode(decryptor.update(cipher_text) + decryptor.finalize())[16:] # skip 16-byte random prefix
  62. xml_length = socket.ntohl(struct.unpack("I", content[:4])[0])
  63. xml_content, receive_id = content[4:4 + xml_length], content[4 + xml_length:].decode("utf-8")
  64. except WeComCryptoError:
  65. raise
  66. except Exception as exc:
  67. raise DecryptError(f"decrypt failed: {exc}") from exc
  68. if receive_id != self.receive_id:
  69. raise DecryptError("receive_id mismatch")
  70. return xml_content
  71. def encrypt(self, plaintext: str, nonce: Optional[str] = None, timestamp: Optional[str] = None) -> str:
  72. nonce = nonce or self._random_nonce()
  73. timestamp = timestamp or str(int(__import__("time").time()))
  74. encrypt = self._encrypt_bytes(plaintext.encode("utf-8"))
  75. root = ET.Element("xml")
  76. for tag, text in (("Encrypt", encrypt), ("MsgSignature", _sha1_signature(self.token, timestamp, nonce, encrypt)), ("TimeStamp", timestamp), ("Nonce", nonce)):
  77. ET.SubElement(root, tag).text = text
  78. return ET.tostring(root, encoding="unicode")
  79. def _encrypt_bytes(self, raw: bytes) -> str:
  80. try:
  81. payload = os.urandom(16) + struct.pack("I", socket.htonl(len(raw))) + raw + self.receive_id.encode("utf-8")
  82. encryptor = self._cipher().encryptor()
  83. return base64.b64encode(encryptor.update(PKCS7Encoder.encode(payload)) + encryptor.finalize()).decode("utf-8")
  84. except Exception as exc:
  85. raise EncryptError(f"encrypt failed: {exc}") from exc
  86. @staticmethod
  87. def _random_nonce(length: int = 10) -> str:
  88. return "".join(secrets.choice("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(length))