Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pkcs11/_pkcs11.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions pkcs11/_pkcs11.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 = \
<CK_SIGN_ADDITIONAL_CONTEXT *> PyMem_Malloc(paramlen)
sign_context_params.hedgeVariant = <CK_HEDGE_TYPE> param.hedge
if param.context:
sign_context_params.pContext = <CK_BYTE *> param.context
sign_context_params.ulContextLen = <CK_ULONG> len(param.context)
else:
sign_context_params.pContext = NULL
sign_context_params.ulContextLen = 0

elif param is None:
self.data.pParameter = NULL
paramlen = 0
Expand Down
39 changes: 39 additions & 0 deletions pkcs11/mechanisms.py
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,45 @@ def __repr__(self) -> str:
return f"<MLDSAParameterSet.{self.name}>"


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"<HedgeType.{self.name}>"


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."""

Expand Down
65 changes: 64 additions & 1 deletion tests/test_ml_dsa.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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)
Loading