Pobierz klucze publiczne Ministerstwa
Ministerstwo publikuje dwa certyfikaty: jeden do szyfrowania tokenu KSeF (KsefTokenEncryption), drugi do szyfrowania klucza sesji (SymmetricKeyEncryption). Endpoint jest publiczny i nie wymaga logowania. Certyfikat przychodzi jako DER zakodowany w Base64.
Szyfrowanie to zawsze RSA-OAEP z SHA-256 i MGF1 z SHA-256. Z innym skrótem serwer nie odszyfruje danych.
import base64import requestsfrom cryptography import x509from cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.primitives.asymmetric import paddingAPI = "https://api-test.ksef.mf.gov.pl/v2"def mf_key(usage: str): certs = requests.get(f"{API}/security/public-key-certificates", timeout=30).json() cert = next(c for c in certs if usage in c["usage"]) der = base64.b64decode(cert["certificate"]) return x509.load_der_x509_certificate(der).public_key()def rsa_oaep(key, data: bytes) -> str: sealed = key.encrypt(data, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) return base64.b64encode(sealed).decode()