import base64 from functools import lru_cache from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import load_der_public_key from app.core.config import get_settings @lru_cache def _get_public_key(): settings = get_settings() der_bytes = base64.b64decode(settings.postal_webhook_public_key_b64) return load_der_public_key(der_bytes) def verify_signature(raw_body: bytes, signature_b64: str) -> bool: try: signature = base64.b64decode(signature_b64) except Exception: return False try: _get_public_key().verify(signature, raw_body, padding.PKCS1v15(), hashes.SHA256()) return True except InvalidSignature: return False