sm-signing 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sm_signing/__init__.py ADDED
@@ -0,0 +1,219 @@
1
+ """sm-signing — an algorithm-agile signing abstraction for agent attestations.
2
+
3
+ The ecosystem hardcodes Ed25519 everywhere; this package is the single seam that
4
+ makes "ML-DSA (FIPS-204) everywhere" a config change instead of a breaking refactor.
5
+ The core — the ``Signer``/``Verifier`` protocols, algorithm dispatch, and did:key /
6
+ multibase encoding — is **pure stdlib, zero runtime dependencies**. Actual crypto
7
+ lives in backends imported lazily behind extras:
8
+
9
+ - ``sm-signing[ed25519]`` — the classical default (real ``cryptography`` signatures).
10
+ - ``sm-signing[pq]`` — ML-DSA / FIPS-204 (the post-quantum target).
11
+
12
+ Usage::
13
+
14
+ from sm_signing import SigAlg, load_signer, verifier_for, generate_secret
15
+
16
+ secret = generate_secret(SigAlg.ED25519) # needs [ed25519]
17
+ signer = load_signer(SigAlg.ED25519, secret)
18
+ sig = signer.sign(b"canonical-payload-bytes")
19
+ v = verifier_for(SigAlg.ED25519, signer.public_key_multibase())
20
+ assert v.verify(b"canonical-payload-bytes", sig)
21
+
22
+ Canonicalization (JCS/RFC 8785, COSE Sig_structure) is the caller's job — a
23
+ ``Signer`` signs exactly the bytes it is given.
24
+
25
+ ``sm_signing.hybrid`` adds the hybrid profile ``sm-signing/hybrid/v1``: an object
26
+ keeps its Ed25519 signature and carries an ML-DSA signature next to it, with a
27
+ verification policy (``classical`` / ``auto`` / ``pq-required``) and a key
28
+ binding between the two keys. Also pure stdlib. Under ``pq-required`` the
29
+ ML-DSA key must come from the verifier's own resolver or a pinned binding.
30
+
31
+ Zero runtime dependencies.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import importlib
37
+ from typing import Protocol, cast
38
+
39
+ from .base import (
40
+ BackendNotInstalled,
41
+ SigAlg,
42
+ Signer,
43
+ SigningError,
44
+ UnsupportedAlgorithm,
45
+ Verifier,
46
+ is_small_order_ed25519_key,
47
+ )
48
+ from .hybrid import (
49
+ BINDING_CONTAINER_MEMBER,
50
+ BINDING_SIGNATURE_MEMBER,
51
+ CONTAINER_VERSION,
52
+ DEFAULT_HYBRID_ALG,
53
+ HYBRID_ALGS,
54
+ HYBRID_DOMAIN_PREFIX,
55
+ HYBRID_PROFILE,
56
+ KEY_BINDING_TYPE,
57
+ MAX_CONTAINER_ENTRIES,
58
+ MAX_CONTAINER_NODES,
59
+ MAX_KID_CHARS,
60
+ MAX_NESTING_DEPTH,
61
+ MAX_PUB_CHARS,
62
+ MAX_SIG_CHARS,
63
+ MAX_SUBJECT_CHARS,
64
+ BindingConflict,
65
+ BindingStore,
66
+ CanonicalBytesSource,
67
+ Canonicalizer,
68
+ EntryResult,
69
+ HybridError,
70
+ HybridResult,
71
+ InMemoryBindingStore,
72
+ KeyResolver,
73
+ KeySource,
74
+ MalformedContainer,
75
+ PinnedBinding,
76
+ Policy,
77
+ PQStatus,
78
+ Reason,
79
+ build_key_binding,
80
+ canonical_binding_bytes,
81
+ complete_container,
82
+ hybrid_signing_input,
83
+ key_id,
84
+ prepare_container,
85
+ prepare_entry,
86
+ strip_signatures,
87
+ verify_hybrid,
88
+ verify_key_binding,
89
+ )
90
+ from .multicodec import (
91
+ MAX_DID_KEY_CHARS,
92
+ MAX_MULTIBASE_CHARS,
93
+ PUBLIC_KEY_SIZES,
94
+ base58btc_decode,
95
+ base58btc_encode,
96
+ did_key,
97
+ multibase_b58btc,
98
+ multicodec_for,
99
+ multikey_decode,
100
+ multikey_encode,
101
+ parse_did_key,
102
+ public_key_multibase,
103
+ )
104
+
105
+ __version__ = "0.3.1"
106
+
107
+ __all__ = [
108
+ "BINDING_CONTAINER_MEMBER",
109
+ "BINDING_SIGNATURE_MEMBER",
110
+ "CONTAINER_VERSION",
111
+ "DEFAULT_HYBRID_ALG",
112
+ "HYBRID_ALGS",
113
+ "HYBRID_DOMAIN_PREFIX",
114
+ "HYBRID_PROFILE",
115
+ "KEY_BINDING_TYPE",
116
+ "MAX_CONTAINER_ENTRIES",
117
+ "MAX_CONTAINER_NODES",
118
+ "MAX_DID_KEY_CHARS",
119
+ "MAX_KID_CHARS",
120
+ "MAX_MULTIBASE_CHARS",
121
+ "MAX_NESTING_DEPTH",
122
+ "MAX_PUB_CHARS",
123
+ "MAX_SIG_CHARS",
124
+ "MAX_SUBJECT_CHARS",
125
+ "PUBLIC_KEY_SIZES",
126
+ "BackendNotInstalled",
127
+ "BindingConflict",
128
+ "BindingStore",
129
+ "CanonicalBytesSource",
130
+ "Canonicalizer",
131
+ "EntryResult",
132
+ "HybridError",
133
+ "HybridResult",
134
+ "InMemoryBindingStore",
135
+ "KeyResolver",
136
+ "KeySource",
137
+ "MalformedContainer",
138
+ "PQStatus",
139
+ "PinnedBinding",
140
+ "Policy",
141
+ "Reason",
142
+ "SigAlg",
143
+ "Signer",
144
+ "SigningError",
145
+ "UnsupportedAlgorithm",
146
+ "Verifier",
147
+ "base58btc_decode",
148
+ "base58btc_encode",
149
+ "build_key_binding",
150
+ "canonical_binding_bytes",
151
+ "complete_container",
152
+ "did_key",
153
+ "generate_secret",
154
+ "hybrid_signing_input",
155
+ "is_small_order_ed25519_key",
156
+ "key_id",
157
+ "load_signer",
158
+ "multibase_b58btc",
159
+ "multicodec_for",
160
+ "multikey_decode",
161
+ "multikey_encode",
162
+ "parse_did_key",
163
+ "prepare_container",
164
+ "prepare_entry",
165
+ "public_key_multibase",
166
+ "strip_signatures",
167
+ "suite_field",
168
+ "verifier_for",
169
+ "verify_hybrid",
170
+ "verify_key_binding",
171
+ ]
172
+
173
+ # alg -> (backend module, install-extra name for the error hint)
174
+ _BACKENDS: dict[SigAlg, tuple[str, str]] = {
175
+ SigAlg.ED25519: ("sm_signing.backends.ed25519", "ed25519"),
176
+ SigAlg.ML_DSA_44: ("sm_signing.backends.mldsa", "pq"),
177
+ SigAlg.ML_DSA_65: ("sm_signing.backends.mldsa", "pq"),
178
+ SigAlg.ML_DSA_87: ("sm_signing.backends.mldsa", "pq"),
179
+ }
180
+
181
+
182
+ class _Backend(Protocol):
183
+ def make_signer(self, alg: SigAlg, secret: bytes) -> Signer: ...
184
+ def make_verifier(self, alg: SigAlg, pub_multibase: str) -> Verifier: ...
185
+ def generate_secret(self, alg: SigAlg) -> bytes: ...
186
+
187
+
188
+ def _load_backend(alg: SigAlg) -> _Backend:
189
+ try:
190
+ module_name, extra = _BACKENDS[alg]
191
+ except KeyError:
192
+ raise UnsupportedAlgorithm(f"no backend registered for {alg}") from None
193
+ try:
194
+ module = importlib.import_module(module_name)
195
+ except (ImportError, AttributeError) as exc:
196
+ # ImportError: the dependency is missing. AttributeError: it is installed
197
+ # but too old to have the classes the backend module names at import.
198
+ raise BackendNotInstalled(f"{alg} requires an optional dependency — install 'sm-signing[{extra}]'") from exc
199
+ return cast("_Backend", module)
200
+
201
+
202
+ def load_signer(alg: SigAlg, secret: bytes) -> Signer:
203
+ """Build a :class:`Signer` for ``alg`` from raw secret-key bytes."""
204
+ return _load_backend(alg).make_signer(alg, secret)
205
+
206
+
207
+ def verifier_for(alg: SigAlg, pub_multibase: str) -> Verifier:
208
+ """Build a :class:`Verifier` for ``alg`` from a multibase base58btc public key."""
209
+ return _load_backend(alg).make_verifier(alg, pub_multibase)
210
+
211
+
212
+ def generate_secret(alg: SigAlg) -> bytes:
213
+ """Generate fresh secret-key bytes for ``alg`` (needs that alg's extra)."""
214
+ return _load_backend(alg).generate_secret(alg)
215
+
216
+
217
+ def suite_field(alg: SigAlg) -> dict[str, str]:
218
+ """The algorithm-agility fields to embed in a signed envelope."""
219
+ return {"signature_suite": str(alg), "alg_agility": "v1"}
@@ -0,0 +1,7 @@
1
+ """Signing backends, imported lazily by ``sm_signing`` dispatch.
2
+
3
+ Each backend module exposes ``make_signer(alg, secret)``, ``make_verifier(alg,
4
+ pub_multibase)``, and ``generate_secret(alg)``. A backend may require an install
5
+ extra (e.g. ``sm-signing[ed25519]``); the extra's absence surfaces as
6
+ ``BackendNotInstalled`` from the dispatch layer.
7
+ """
@@ -0,0 +1,64 @@
1
+ """Ed25519 backend — the classical default suite (real ``cryptography`` signatures).
2
+
3
+ Requires the ``[ed25519]`` extra (the ``cryptography`` package). Imported lazily,
4
+ so the zero-dep core never pulls ``cryptography`` in unless Ed25519 is actually used.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from cryptography.exceptions import InvalidSignature as _CryptoInvalidSignature
10
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
11
+ Ed25519PrivateKey,
12
+ Ed25519PublicKey,
13
+ )
14
+
15
+ from ..base import SigAlg, is_small_order_ed25519_key
16
+ from ..multicodec import multibase_decode, public_key_multibase
17
+
18
+ _ALG = SigAlg.ED25519
19
+
20
+
21
+ class _Ed25519Signer:
22
+ alg = _ALG
23
+
24
+ def __init__(self, secret: bytes) -> None:
25
+ self._sk = Ed25519PrivateKey.from_private_bytes(secret)
26
+ self._pub = self._sk.public_key().public_bytes_raw()
27
+
28
+ def sign(self, payload: bytes) -> bytes:
29
+ return self._sk.sign(payload)
30
+
31
+ def public_key_bytes(self) -> bytes:
32
+ return self._pub
33
+
34
+ def public_key_multibase(self) -> str:
35
+ return public_key_multibase(self.alg, self._pub)
36
+
37
+
38
+ class _Ed25519Verifier:
39
+ alg = _ALG
40
+
41
+ def __init__(self, pub: bytes) -> None:
42
+ if is_small_order_ed25519_key(pub):
43
+ # One constant signature verifies every message under such a key.
44
+ raise ValueError("Ed25519 public key is a small-order point; it identifies nobody")
45
+ self._pk = Ed25519PublicKey.from_public_bytes(pub)
46
+
47
+ def verify(self, payload: bytes, signature: bytes) -> bool:
48
+ try:
49
+ self._pk.verify(signature, payload)
50
+ return True
51
+ except _CryptoInvalidSignature:
52
+ return False
53
+
54
+
55
+ def make_signer(alg: SigAlg, secret: bytes) -> _Ed25519Signer:
56
+ return _Ed25519Signer(secret)
57
+
58
+
59
+ def make_verifier(alg: SigAlg, pub_multibase: str) -> _Ed25519Verifier:
60
+ return _Ed25519Verifier(multibase_decode(pub_multibase))
61
+
62
+
63
+ def generate_secret(alg: SigAlg) -> bytes:
64
+ return Ed25519PrivateKey.generate().private_bytes_raw()
@@ -0,0 +1,106 @@
1
+ """ML-DSA (FIPS-204) backend — the post-quantum target suite.
2
+
3
+ Requires the ``[pq]`` extra: ``cryptography>=48`` (built against OpenSSL >= 3.5),
4
+ which exposes ML-DSA natively via ``cryptography.hazmat.primitives.asymmetric.mldsa``.
5
+ Imported lazily, so the zero-dep core never pulls it in unless an ML-DSA suite is
6
+ actually used.
7
+
8
+ Version floor, as tested: the ``mldsa`` module does not exist before
9
+ ``cryptography`` 47.0 (import fails), and the 47.0 wheels import it but raise
10
+ "not supported by this backend" for every ML-DSA operation. 48.0 is the first
11
+ release whose wheels sign and verify. Both failure modes surface from the
12
+ dispatch layer as ``BackendNotInstalled``.
13
+
14
+ The ``secret`` is the 32-byte ML-DSA seed (``private_bytes_raw`` / ``from_seed_bytes``);
15
+ public keys and signatures are the full FIPS-204 sizes (e.g. ML-DSA-65: 1952-byte
16
+ public key, 3309-byte signature).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Any
22
+
23
+ from cryptography.exceptions import InvalidSignature as _CryptoInvalidSignature
24
+ from cryptography.exceptions import UnsupportedAlgorithm as _CryptoUnsupportedAlgorithm
25
+ from cryptography.hazmat.primitives.asymmetric import mldsa
26
+
27
+ from ..base import BackendNotInstalled, SigAlg, UnsupportedAlgorithm
28
+ from ..multicodec import multibase_decode, public_key_multibase
29
+
30
+ _PRIVATE: dict[SigAlg, Any] = {
31
+ SigAlg.ML_DSA_44: mldsa.MLDSA44PrivateKey,
32
+ SigAlg.ML_DSA_65: mldsa.MLDSA65PrivateKey,
33
+ SigAlg.ML_DSA_87: mldsa.MLDSA87PrivateKey,
34
+ }
35
+ _PUBLIC: dict[SigAlg, Any] = {
36
+ SigAlg.ML_DSA_44: mldsa.MLDSA44PublicKey,
37
+ SigAlg.ML_DSA_65: mldsa.MLDSA65PublicKey,
38
+ SigAlg.ML_DSA_87: mldsa.MLDSA87PublicKey,
39
+ }
40
+
41
+
42
+ def _require(alg: SigAlg) -> None:
43
+ if alg not in _PRIVATE:
44
+ raise UnsupportedAlgorithm(f"{alg} is not an ML-DSA suite")
45
+
46
+
47
+ def _unavailable(alg: SigAlg) -> BackendNotInstalled:
48
+ return BackendNotInstalled(
49
+ f"{alg} is not supported by the installed cryptography build "
50
+ "(needs cryptography >= 48 with OpenSSL >= 3.5) — install 'sm-signing[pq]'"
51
+ )
52
+
53
+
54
+ class _MLDSASigner:
55
+ def __init__(self, alg: SigAlg, secret: bytes) -> None:
56
+ _require(alg)
57
+ self.alg = alg
58
+ try:
59
+ self._sk = _PRIVATE[alg].from_seed_bytes(secret)
60
+ except _CryptoUnsupportedAlgorithm as exc:
61
+ raise _unavailable(alg) from exc
62
+ self._pub: bytes = self._sk.public_key().public_bytes_raw()
63
+
64
+ def sign(self, payload: bytes) -> bytes:
65
+ result: bytes = self._sk.sign(payload)
66
+ return result
67
+
68
+ def public_key_bytes(self) -> bytes:
69
+ return self._pub
70
+
71
+ def public_key_multibase(self) -> str:
72
+ return public_key_multibase(self.alg, self._pub)
73
+
74
+
75
+ class _MLDSAVerifier:
76
+ def __init__(self, alg: SigAlg, pub: bytes) -> None:
77
+ _require(alg)
78
+ self.alg = alg
79
+ try:
80
+ self._pk = _PUBLIC[alg].from_public_bytes(pub)
81
+ except _CryptoUnsupportedAlgorithm as exc:
82
+ raise _unavailable(alg) from exc
83
+
84
+ def verify(self, payload: bytes, signature: bytes) -> bool:
85
+ try:
86
+ self._pk.verify(signature, payload)
87
+ return True
88
+ except _CryptoInvalidSignature:
89
+ return False
90
+
91
+
92
+ def make_signer(alg: SigAlg, secret: bytes) -> _MLDSASigner:
93
+ return _MLDSASigner(alg, secret)
94
+
95
+
96
+ def make_verifier(alg: SigAlg, pub_multibase: str) -> _MLDSAVerifier:
97
+ return _MLDSAVerifier(alg, multibase_decode(pub_multibase))
98
+
99
+
100
+ def generate_secret(alg: SigAlg) -> bytes:
101
+ _require(alg)
102
+ try:
103
+ seed: bytes = _PRIVATE[alg].generate().private_bytes_raw()
104
+ except _CryptoUnsupportedAlgorithm as exc:
105
+ raise _unavailable(alg) from exc
106
+ return seed
sm_signing/base.py ADDED
@@ -0,0 +1,102 @@
1
+ """Core signing contracts — zero runtime dependencies.
2
+
3
+ Defines the algorithm-agile ``Signer``/``Verifier`` protocols, the ``SigAlg``
4
+ enumeration, and the exception hierarchy. No cryptography is imported here; the
5
+ actual signing lives in ``sm_signing.backends.*`` behind install extras, imported
6
+ lazily by the dispatch functions in ``sm_signing.__init__``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from enum import StrEnum
12
+ from typing import Protocol, runtime_checkable
13
+
14
+
15
+ class SigAlg(StrEnum):
16
+ """Supported signature suites.
17
+
18
+ ``ED25519`` is the classical default (real ``cryptography`` signatures — fast,
19
+ ubiquitous); the ``ML_DSA_*`` suites are the post-quantum (FIPS-204) target. Note:
20
+ post-quantum cryptography, not "quantum" anything.
21
+ """
22
+
23
+ ED25519 = "ed25519"
24
+ ML_DSA_44 = "ml-dsa-44"
25
+ ML_DSA_65 = "ml-dsa-65"
26
+ ML_DSA_87 = "ml-dsa-87"
27
+
28
+ @property
29
+ def is_post_quantum(self) -> bool:
30
+ """True for the ML-DSA suites."""
31
+ return self.name.startswith("ML_DSA")
32
+
33
+
34
+ #: The seven y-coordinate encodings (bit 255, the sign of x, cleared) of the eight
35
+ #: edwards25519 points of order 1, 2, 4 or 8, including the non-canonical forms
36
+ #: ``p`` and ``p + 1``. Nobody holds a private key for such a point, and a
37
+ #: signature that verifies for one message under it verifies for every message.
38
+ _ED25519_SMALL_ORDER_Y: frozenset[bytes] = frozenset(
39
+ bytes.fromhex(encoded)
40
+ for encoded in (
41
+ "0000000000000000000000000000000000000000000000000000000000000000",
42
+ "0100000000000000000000000000000000000000000000000000000000000000",
43
+ "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
44
+ "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
45
+ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
46
+ "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
47
+ "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
48
+ )
49
+ )
50
+
51
+
52
+ def is_small_order_ed25519_key(public_key: bytes) -> bool:
53
+ """True if ``public_key`` (32 raw bytes) encodes an edwards25519 point of small order.
54
+
55
+ Such a key identifies nobody: no private key exists for it, and one constant
56
+ signature verifies every message under it. Verifiers reject these keys. Pure
57
+ standard library: a comparison against the fixed list of encodings, with the
58
+ sign bit ignored.
59
+ """
60
+ if len(public_key) != 32:
61
+ return False
62
+ masked = bytes(public_key[:31]) + bytes([public_key[31] & 0x7F])
63
+ return masked in _ED25519_SMALL_ORDER_Y
64
+
65
+
66
+ class SigningError(Exception):
67
+ """Base class for all signing errors."""
68
+
69
+
70
+ class UnsupportedAlgorithm(SigningError):
71
+ """The requested ``SigAlg`` has no registered backend or multicodec."""
72
+
73
+
74
+ class BackendNotInstalled(SigningError):
75
+ """The backend for an algorithm exists but its install extra is missing."""
76
+
77
+
78
+ @runtime_checkable
79
+ class Signer(Protocol):
80
+ """Produces detached signatures over raw bytes.
81
+
82
+ Canonicalization of any structured payload (JCS / RFC 8785, COSE Sig_structure,
83
+ etc.) is the *caller's* responsibility — a ``Signer`` signs exactly the bytes given.
84
+ """
85
+
86
+ alg: SigAlg
87
+
88
+ def sign(self, payload: bytes) -> bytes: ...
89
+
90
+ def public_key_bytes(self) -> bytes: ...
91
+
92
+ def public_key_multibase(self) -> str: ...
93
+
94
+
95
+ @runtime_checkable
96
+ class Verifier(Protocol):
97
+ """Verifies a detached signature over raw bytes. Never raises on a bad
98
+ signature — returns ``False``."""
99
+
100
+ alg: SigAlg
101
+
102
+ def verify(self, payload: bytes, signature: bytes) -> bool: ...