authentik.lib.jwt_mldsa
ML-DSA (FIPS 204) signature algorithms for PyJWT, per RFC 9964.
PyJWT ships no post-quantum algorithms. This module registers ML-DSA-44, ML-DSA-65 and
ML-DSA-87 with PyJWT's global JWS instance, backed by cryptography's ML-DSA keys, so every
existing jwt.encode / jwt.decode call site can sign and verify ML-DSA tokens unchanged.
JWK representation (RFC 9964): kty is AKP, alg names the parameter set, pub carries the
raw public key and priv the raw private key, both base64url encoded.
This module is imported during process setup (see authentik.root.setup) and must not import Django.
1"""ML-DSA (FIPS 204) signature algorithms for PyJWT, per RFC 9964. 2 3PyJWT ships no post-quantum algorithms. This module registers `ML-DSA-44`, `ML-DSA-65` and 4`ML-DSA-87` with PyJWT's global JWS instance, backed by cryptography's ML-DSA keys, so every 5existing `jwt.encode` / `jwt.decode` call site can sign and verify ML-DSA tokens unchanged. 6 7JWK representation (RFC 9964): `kty` is `AKP`, `alg` names the parameter set, `pub` carries the 8raw public key and `priv` the raw private key, both base64url encoded. 9 10This module is imported during process setup (see authentik.root.setup) and must not import 11Django.""" 12 13from json import loads 14from typing import Any 15 16from cryptography.exceptions import InternalError, InvalidSignature, UnsupportedAlgorithm 17from cryptography.hazmat.primitives.asymmetric import mldsa 18from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_public_key 19from jwt import PyJWK, register_algorithm 20from jwt.algorithms import Algorithm 21from jwt.exceptions import InvalidKeyError 22from jwt.utils import base64url_decode, base64url_encode 23 24JWK_KTY_AKP = "AKP" 25 26# Raised by cryptography when key material is malformed (ValueError) or when OpenSSL has no 27# implementation for the algorithm in the current configuration, for example ML-DSA under a FIPS 28# provider that predates it (InternalError / UnsupportedAlgorithm). All three mean the key is 29# unusable here, so they surface as InvalidKeyError for the JWT call sites to handle. 30KEY_LOAD_ERRORS = (ValueError, InternalError, UnsupportedAlgorithm) 31 32MLDSAKey = ( 33 mldsa.MLDSA44PrivateKey 34 | mldsa.MLDSA44PublicKey 35 | mldsa.MLDSA65PrivateKey 36 | mldsa.MLDSA65PublicKey 37 | mldsa.MLDSA87PrivateKey 38 | mldsa.MLDSA87PublicKey 39) 40 41# JOSE algorithm name -> (private key class, public key class) 42MLDSA_ALGORITHMS: dict[str, tuple[type, type]] = { 43 "ML-DSA-44": (mldsa.MLDSA44PrivateKey, mldsa.MLDSA44PublicKey), 44 "ML-DSA-65": (mldsa.MLDSA65PrivateKey, mldsa.MLDSA65PublicKey), 45 "ML-DSA-87": (mldsa.MLDSA87PrivateKey, mldsa.MLDSA87PublicKey), 46} 47 48 49class MLDSAAlgorithm(Algorithm): 50 """PyJWT signature algorithm for one ML-DSA parameter set""" 51 52 def __init__(self, name: str): 53 self.name = name 54 self.private_key_cls, self.public_key_cls = MLDSA_ALGORITHMS[name] 55 self._crypto_key_types = (self.private_key_cls, self.public_key_cls) 56 57 def prepare_key(self, key: Any) -> MLDSAKey: 58 if isinstance(key, str | bytes): 59 key_bytes = key.encode("utf-8") if isinstance(key, str) else key 60 try: 61 if b"-----BEGIN PUBLIC" in key_bytes: 62 key = load_pem_public_key(key_bytes) 63 elif b"-----BEGIN PRIVATE" in key_bytes: 64 key = load_pem_private_key(key_bytes, password=None) 65 else: 66 raise InvalidKeyError("Not a PEM public or private key") 67 except KEY_LOAD_ERRORS as exc: 68 raise InvalidKeyError(f"Unable to load {self.name} key: {exc}") from exc 69 if not isinstance(key, self._crypto_key_types): 70 raise InvalidKeyError(f"Expected a {self.name} key, got {type(key).__name__}") 71 return key 72 73 def sign(self, msg: bytes, key: Any) -> bytes: 74 if not isinstance(key, self.private_key_cls): 75 raise InvalidKeyError(f"A {self.name} private key is required to sign") 76 return key.sign(msg) 77 78 def verify(self, msg: bytes, key: Any, sig: bytes) -> bool: 79 public_key = key.public_key() if isinstance(key, self.private_key_cls) else key 80 try: 81 public_key.verify(sig, msg) 82 return True 83 except InvalidSignature: 84 return False 85 86 @staticmethod 87 def to_jwk(key_obj: Any, as_dict: bool = False) -> dict | str: 88 name = MLDSAAlgorithm.algorithm_for_key(key_obj) 89 private_key_cls, _ = MLDSA_ALGORITHMS[name] 90 jwk: dict[str, str] = {"kty": JWK_KTY_AKP, "alg": name} 91 if isinstance(key_obj, private_key_cls): 92 jwk["priv"] = base64url_encode(key_obj.private_bytes_raw()).decode("ascii") 93 key_obj = key_obj.public_key() 94 jwk["pub"] = base64url_encode(key_obj.public_bytes_raw()).decode("ascii") 95 if as_dict: 96 return jwk 97 from json import dumps 98 99 return dumps(jwk) 100 101 @staticmethod 102 def from_jwk(jwk: str | dict) -> MLDSAKey: 103 data = loads(jwk) if isinstance(jwk, str) else jwk 104 if data.get("kty") != JWK_KTY_AKP: 105 raise InvalidKeyError("Not an AKP key") 106 name = data.get("alg") 107 if name not in MLDSA_ALGORITHMS: 108 raise InvalidKeyError(f"Unsupported AKP algorithm: {name}") 109 private_key_cls, public_key_cls = MLDSA_ALGORITHMS[name] 110 try: 111 if "priv" in data: 112 return private_key_cls.from_private_bytes(base64url_decode(data["priv"])) 113 if "pub" in data: 114 return public_key_cls.from_public_bytes(base64url_decode(data["pub"])) 115 except KEY_LOAD_ERRORS as exc: 116 raise InvalidKeyError(f"Invalid {name} key: {exc}") from exc 117 raise InvalidKeyError("AKP key has neither pub nor priv") 118 119 @staticmethod 120 def algorithm_for_key(key: Any) -> str: 121 """Return the JOSE algorithm name for an ML-DSA key, or raise ValueError""" 122 for name, classes in MLDSA_ALGORITHMS.items(): 123 if isinstance(key, classes): 124 return name 125 raise ValueError(f"Not an ML-DSA key: {type(key).__name__}") 126 127 128def key_from_jwk(jwk: dict) -> tuple[Any, str]: 129 """Load a JWK into a cryptography key and return it with its JOSE algorithm. 130 131 PyJWT's own JWK loader only knows the key types it ships with, so AKP keys are handled here 132 and everything else is delegated to PyJWK.""" 133 if jwk.get("kty") == JWK_KTY_AKP: 134 return MLDSAAlgorithm.from_jwk(jwk), jwk["alg"] 135 parsed = PyJWK.from_dict(jwk) 136 return parsed.key, parsed.algorithm_name 137 138 139def register_mldsa_algorithms(): 140 """Register the ML-DSA algorithms with PyJWT's global JWS instance (idempotent)""" 141 for name in MLDSA_ALGORITHMS: 142 try: 143 register_algorithm(name, MLDSAAlgorithm(name)) 144 except ValueError: 145 # Already registered 146 pass
50class MLDSAAlgorithm(Algorithm): 51 """PyJWT signature algorithm for one ML-DSA parameter set""" 52 53 def __init__(self, name: str): 54 self.name = name 55 self.private_key_cls, self.public_key_cls = MLDSA_ALGORITHMS[name] 56 self._crypto_key_types = (self.private_key_cls, self.public_key_cls) 57 58 def prepare_key(self, key: Any) -> MLDSAKey: 59 if isinstance(key, str | bytes): 60 key_bytes = key.encode("utf-8") if isinstance(key, str) else key 61 try: 62 if b"-----BEGIN PUBLIC" in key_bytes: 63 key = load_pem_public_key(key_bytes) 64 elif b"-----BEGIN PRIVATE" in key_bytes: 65 key = load_pem_private_key(key_bytes, password=None) 66 else: 67 raise InvalidKeyError("Not a PEM public or private key") 68 except KEY_LOAD_ERRORS as exc: 69 raise InvalidKeyError(f"Unable to load {self.name} key: {exc}") from exc 70 if not isinstance(key, self._crypto_key_types): 71 raise InvalidKeyError(f"Expected a {self.name} key, got {type(key).__name__}") 72 return key 73 74 def sign(self, msg: bytes, key: Any) -> bytes: 75 if not isinstance(key, self.private_key_cls): 76 raise InvalidKeyError(f"A {self.name} private key is required to sign") 77 return key.sign(msg) 78 79 def verify(self, msg: bytes, key: Any, sig: bytes) -> bool: 80 public_key = key.public_key() if isinstance(key, self.private_key_cls) else key 81 try: 82 public_key.verify(sig, msg) 83 return True 84 except InvalidSignature: 85 return False 86 87 @staticmethod 88 def to_jwk(key_obj: Any, as_dict: bool = False) -> dict | str: 89 name = MLDSAAlgorithm.algorithm_for_key(key_obj) 90 private_key_cls, _ = MLDSA_ALGORITHMS[name] 91 jwk: dict[str, str] = {"kty": JWK_KTY_AKP, "alg": name} 92 if isinstance(key_obj, private_key_cls): 93 jwk["priv"] = base64url_encode(key_obj.private_bytes_raw()).decode("ascii") 94 key_obj = key_obj.public_key() 95 jwk["pub"] = base64url_encode(key_obj.public_bytes_raw()).decode("ascii") 96 if as_dict: 97 return jwk 98 from json import dumps 99 100 return dumps(jwk) 101 102 @staticmethod 103 def from_jwk(jwk: str | dict) -> MLDSAKey: 104 data = loads(jwk) if isinstance(jwk, str) else jwk 105 if data.get("kty") != JWK_KTY_AKP: 106 raise InvalidKeyError("Not an AKP key") 107 name = data.get("alg") 108 if name not in MLDSA_ALGORITHMS: 109 raise InvalidKeyError(f"Unsupported AKP algorithm: {name}") 110 private_key_cls, public_key_cls = MLDSA_ALGORITHMS[name] 111 try: 112 if "priv" in data: 113 return private_key_cls.from_private_bytes(base64url_decode(data["priv"])) 114 if "pub" in data: 115 return public_key_cls.from_public_bytes(base64url_decode(data["pub"])) 116 except KEY_LOAD_ERRORS as exc: 117 raise InvalidKeyError(f"Invalid {name} key: {exc}") from exc 118 raise InvalidKeyError("AKP key has neither pub nor priv") 119 120 @staticmethod 121 def algorithm_for_key(key: Any) -> str: 122 """Return the JOSE algorithm name for an ML-DSA key, or raise ValueError""" 123 for name, classes in MLDSA_ALGORITHMS.items(): 124 if isinstance(key, classes): 125 return name 126 raise ValueError(f"Not an ML-DSA key: {type(key).__name__}")
PyJWT signature algorithm for one ML-DSA parameter set
58 def prepare_key(self, key: Any) -> MLDSAKey: 59 if isinstance(key, str | bytes): 60 key_bytes = key.encode("utf-8") if isinstance(key, str) else key 61 try: 62 if b"-----BEGIN PUBLIC" in key_bytes: 63 key = load_pem_public_key(key_bytes) 64 elif b"-----BEGIN PRIVATE" in key_bytes: 65 key = load_pem_private_key(key_bytes, password=None) 66 else: 67 raise InvalidKeyError("Not a PEM public or private key") 68 except KEY_LOAD_ERRORS as exc: 69 raise InvalidKeyError(f"Unable to load {self.name} key: {exc}") from exc 70 if not isinstance(key, self._crypto_key_types): 71 raise InvalidKeyError(f"Expected a {self.name} key, got {type(key).__name__}") 72 return key
Performs necessary validation and conversions on the key and returns the key value in the proper format for sign() and verify().
74 def sign(self, msg: bytes, key: Any) -> bytes: 75 if not isinstance(key, self.private_key_cls): 76 raise InvalidKeyError(f"A {self.name} private key is required to sign") 77 return key.sign(msg)
Returns a digital signature for the specified message using the specified key value.
79 def verify(self, msg: bytes, key: Any, sig: bytes) -> bool: 80 public_key = key.public_key() if isinstance(key, self.private_key_cls) else key 81 try: 82 public_key.verify(sig, msg) 83 return True 84 except InvalidSignature: 85 return False
Verifies that the specified digital signature is valid for the specified message and key values.
87 @staticmethod 88 def to_jwk(key_obj: Any, as_dict: bool = False) -> dict | str: 89 name = MLDSAAlgorithm.algorithm_for_key(key_obj) 90 private_key_cls, _ = MLDSA_ALGORITHMS[name] 91 jwk: dict[str, str] = {"kty": JWK_KTY_AKP, "alg": name} 92 if isinstance(key_obj, private_key_cls): 93 jwk["priv"] = base64url_encode(key_obj.private_bytes_raw()).decode("ascii") 94 key_obj = key_obj.public_key() 95 jwk["pub"] = base64url_encode(key_obj.public_bytes_raw()).decode("ascii") 96 if as_dict: 97 return jwk 98 from json import dumps 99 100 return dumps(jwk)
Serializes a given key into a JWK
102 @staticmethod 103 def from_jwk(jwk: str | dict) -> MLDSAKey: 104 data = loads(jwk) if isinstance(jwk, str) else jwk 105 if data.get("kty") != JWK_KTY_AKP: 106 raise InvalidKeyError("Not an AKP key") 107 name = data.get("alg") 108 if name not in MLDSA_ALGORITHMS: 109 raise InvalidKeyError(f"Unsupported AKP algorithm: {name}") 110 private_key_cls, public_key_cls = MLDSA_ALGORITHMS[name] 111 try: 112 if "priv" in data: 113 return private_key_cls.from_private_bytes(base64url_decode(data["priv"])) 114 if "pub" in data: 115 return public_key_cls.from_public_bytes(base64url_decode(data["pub"])) 116 except KEY_LOAD_ERRORS as exc: 117 raise InvalidKeyError(f"Invalid {name} key: {exc}") from exc 118 raise InvalidKeyError("AKP key has neither pub nor priv")
Deserializes a given key from JWK back into a key object
120 @staticmethod 121 def algorithm_for_key(key: Any) -> str: 122 """Return the JOSE algorithm name for an ML-DSA key, or raise ValueError""" 123 for name, classes in MLDSA_ALGORITHMS.items(): 124 if isinstance(key, classes): 125 return name 126 raise ValueError(f"Not an ML-DSA key: {type(key).__name__}")
Return the JOSE algorithm name for an ML-DSA key, or raise ValueError
129def key_from_jwk(jwk: dict) -> tuple[Any, str]: 130 """Load a JWK into a cryptography key and return it with its JOSE algorithm. 131 132 PyJWT's own JWK loader only knows the key types it ships with, so AKP keys are handled here 133 and everything else is delegated to PyJWK.""" 134 if jwk.get("kty") == JWK_KTY_AKP: 135 return MLDSAAlgorithm.from_jwk(jwk), jwk["alg"] 136 parsed = PyJWK.from_dict(jwk) 137 return parsed.key, parsed.algorithm_name
Load a JWK into a cryptography key and return it with its JOSE algorithm.
PyJWT's own JWK loader only knows the key types it ships with, so AKP keys are handled here and everything else is delegated to PyJWK.
140def register_mldsa_algorithms(): 141 """Register the ML-DSA algorithms with PyJWT's global JWS instance (idempotent)""" 142 for name in MLDSA_ALGORITHMS: 143 try: 144 register_algorithm(name, MLDSAAlgorithm(name)) 145 except ValueError: 146 # Already registered 147 pass
Register the ML-DSA algorithms with PyJWT's global JWS instance (idempotent)