Fetch the Ministry public keys
The Ministry publishes two certificates: one for encrypting the KSeF token (KsefTokenEncryption), the other for encrypting the session key (SymmetricKeyEncryption). The endpoint is public and needs no login. The certificate arrives as Base64-encoded DER.
Encryption is always RSA-OAEP with SHA-256 and MGF1 with SHA-256. With any other hash the server cannot decrypt the data.
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()