diff --git a/pkcs11/_pkcs11.pxd b/pkcs11/_pkcs11.pxd index cfa5380..743b124 100644 --- a/pkcs11/_pkcs11.pxd +++ b/pkcs11/_pkcs11.pxd @@ -16,6 +16,7 @@ cdef extern from '../extern/cryptoki.h': ctypedef CK_ULONG CK_ATTRIBUTE_TYPE ctypedef CK_ULONG CK_EC_KDF_TYPE ctypedef CK_ULONG CK_FLAGS + ctypedef CK_ULONG CK_HEDGE_TYPE ctypedef CK_ULONG CK_MECHANISM_TYPE ctypedef CK_ULONG CK_OBJECT_HANDLE ctypedef CK_ULONG CK_RSA_PKCS_MGF_TYPE @@ -280,6 +281,11 @@ cdef extern from '../extern/cryptoki.h': CK_ULONG ulContextDataLen CK_BYTE *pContextData + ctypedef struct CK_SIGN_ADDITIONAL_CONTEXT: + CK_HEDGE_TYPE hedgeVariant + CK_BYTE *pContext + CK_ULONG ulContextLen + ctypedef struct CK_INTERFACE: CK_UTF8CHAR *pInterfaceName void *pFunctionList diff --git a/pkcs11/_pkcs11.pyx b/pkcs11/_pkcs11.pyx index 75307d6..c2f9c80 100644 --- a/pkcs11/_pkcs11.pyx +++ b/pkcs11/_pkcs11.pyx @@ -179,6 +179,7 @@ cdef class MechanismWithParam: cdef CK_AES_CBC_ENCRYPT_DATA_PARAMS *aes_cbc_params cdef CK_GCM_PARAMS *gcm_params cdef CK_AES_CTR_PARAMS *aes_ctr_params + cdef CK_SIGN_ADDITIONAL_CONTEXT *sign_context_params # Unpack mechanism parameters @@ -302,6 +303,20 @@ cdef class MechanismWithParam: aes_ctr_params.ulCounterBits = (16 - len(param.nonce)) * 8 aes_ctr_params.cb = param.nonce + b"\x00" * (15 - len(param.nonce)) + b"\x01" + elif mechanism == Mechanism.ML_DSA and param is not None: + if not isinstance(param, SignAdditionalContext): + raise ArgumentsBad("ML_DSA parameters must be a SignAdditionalContext") + paramlen = sizeof(CK_SIGN_ADDITIONAL_CONTEXT) + self.param = sign_context_params = \ + PyMem_Malloc(paramlen) + sign_context_params.hedgeVariant = param.hedge + if param.context: + sign_context_params.pContext = param.context + sign_context_params.ulContextLen = len(param.context) + else: + sign_context_params.pContext = NULL + sign_context_params.ulContextLen = 0 + elif param is None: self.data.pParameter = NULL paramlen = 0 diff --git a/pkcs11/mechanisms.py b/pkcs11/mechanisms.py index 2b09d32..68ef5bb 100644 --- a/pkcs11/mechanisms.py +++ b/pkcs11/mechanisms.py @@ -833,6 +833,45 @@ def __repr__(self) -> str: return f"" +class HedgeType(IntEnum): + """Hedging variants for ML-DSA signatures (PKCS#11 v3.2 ``CK_HEDGE_TYPE``).""" + + PREFERRED = 0x00000000 + """Hedged signing if the token supports it, deterministic otherwise.""" + REQUIRED = 0x00000001 + """Hedged signing (FIPS 204 randomized variant); fail if not supported.""" + DETERMINISTIC_REQUIRED = 0x00000002 + """Deterministic signing (FIPS 204 deterministic variant); fail if not supported.""" + + def __repr__(self) -> str: + return f"" + + +class SignAdditionalContext: + """ + Parameters for ML-DSA signing and verification + (PKCS#11 v3.2 ``CK_SIGN_ADDITIONAL_CONTEXT``). + + :param context: the FIPS 204 context string, at most 255 bytes. + ``None`` or ``b""`` means an empty context. + :param hedge: the hedging variant, see :class:`HedgeType`. It applies to + signing; tokens ignore it when verifying. + """ + + context: bytes | None + hedge: HedgeType + + def __init__( + self, context: bytes | None = None, hedge: HedgeType = HedgeType.PREFERRED + ) -> None: + if context is not None and len(context) > 255: + raise ArgumentsBad("The context must be at most 255 bytes") + if not isinstance(hedge, HedgeType): + raise ArgumentsBad("`hedge` must be a HedgeType") + self.context = context + self.hedge = hedge + + class GCMParams: """Parameters for AES-GCM mode.""" diff --git a/tests/test_ml_dsa.py b/tests/test_ml_dsa.py index 44b6429..1893472 100644 --- a/tests/test_ml_dsa.py +++ b/tests/test_ml_dsa.py @@ -1,6 +1,6 @@ import pkcs11 from pkcs11 import Attribute, KeyType, Mechanism -from pkcs11.mechanisms import MLDSAParameterSet +from pkcs11.mechanisms import HedgeType, MLDSAParameterSet, SignAdditionalContext from . import TestCase, requires @@ -60,3 +60,66 @@ def test_sign_verify_wrong_data(self): def test_missing_parameter_set_raises(self): with self.assertRaises(pkcs11.exceptions.ArgumentsBad): self.session.generate_keypair(KeyType.ML_DSA) + + def _keypair(self): + return self.session.generate_keypair( + KeyType.ML_DSA, + public_template={Attribute.PARAMETER_SET: MLDSAParameterSet.ML_DSA_65}, + ) + + @requires(Mechanism.ML_DSA_KEY_PAIR_GEN, Mechanism.ML_DSA) + def test_sign_verify_context(self): + pub, priv = self._keypair() + data = b"Hello, post-quantum world!" + ctx = SignAdditionalContext(context=b"python-pkcs11 test") + sig = priv.sign(data, mechanism_param=ctx) + self.assertTrue(pub.verify(data, sig, mechanism_param=ctx)) + # The context is part of the signed message: another context, or + # none, must not verify. + other = SignAdditionalContext(context=b"another context") + self.assertFalse(pub.verify(data, sig, mechanism_param=other)) + self.assertFalse(pub.verify(data, sig)) + + @requires(Mechanism.ML_DSA_KEY_PAIR_GEN, Mechanism.ML_DSA) + def test_empty_context_matches_no_parameter(self): + pub, priv = self._keypair() + data = b"Hello, post-quantum world!" + sig = priv.sign(data, mechanism_param=SignAdditionalContext()) + self.assertTrue(pub.verify(data, sig)) + sig = priv.sign(data) + self.assertTrue(pub.verify(data, sig, mechanism_param=SignAdditionalContext(b""))) + + @requires(Mechanism.ML_DSA_KEY_PAIR_GEN, Mechanism.ML_DSA) + def test_deterministic(self): + pub, priv = self._keypair() + data = b"Hello, post-quantum world!" + param = SignAdditionalContext(hedge=HedgeType.DETERMINISTIC_REQUIRED) + sig1 = priv.sign(data, mechanism_param=param) + sig2 = priv.sign(data, mechanism_param=param) + self.assertEqual(sig1, sig2) + self.assertTrue(pub.verify(data, sig1)) + + @requires(Mechanism.ML_DSA_KEY_PAIR_GEN, Mechanism.ML_DSA) + def test_hedged(self): + pub, priv = self._keypair() + data = b"Hello, post-quantum world!" + param = SignAdditionalContext(hedge=HedgeType.REQUIRED) + sig1 = priv.sign(data, mechanism_param=param) + sig2 = priv.sign(data, mechanism_param=param) + self.assertNotEqual(sig1, sig2) + self.assertTrue(pub.verify(data, sig1)) + self.assertTrue(pub.verify(data, sig2)) + + @requires(Mechanism.ML_DSA_KEY_PAIR_GEN, Mechanism.ML_DSA) + def test_wrong_parameter_type_raises(self): + _, priv = self._keypair() + with self.assertRaises(pkcs11.exceptions.ArgumentsBad): + priv.sign(b"data", mechanism_param=(0, b"context")) + + def test_context_too_long_raises(self): + with self.assertRaises(pkcs11.exceptions.ArgumentsBad): + SignAdditionalContext(context=b"x" * 256) + + def test_hedge_must_be_hedge_type(self): + with self.assertRaises(pkcs11.exceptions.ArgumentsBad): + SignAdditionalContext(hedge=1)