pqlock 0.1.0__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.
- pqlock/__init__.py +41 -0
- pqlock/_suite.py +562 -0
- pqlock/audit/__init__.py +367 -0
- pqlock/errors.py +29 -0
- pqlock/keyset/__init__.py +271 -0
- pqlock/legacy/__init__.py +215 -0
- pqlock/policy/__init__.py +146 -0
- pqlock/rotate/__init__.py +163 -0
- pqlock/seal/__init__.py +150 -0
- pqlock/seal_batch/__init__.py +107 -0
- pqlock/sign/__init__.py +94 -0
- pqlock/stream/__init__.py +164 -0
- pqlock/tls/__init__.py +13 -0
- pqlock/tokens/__init__.py +271 -0
- pqlock/webhooks/__init__.py +244 -0
- pqlock-0.1.0.dist-info/METADATA +85 -0
- pqlock-0.1.0.dist-info/RECORD +21 -0
- pqlock-0.1.0.dist-info/WHEEL +5 -0
- pqlock-0.1.0.dist-info/licenses/LICENSE +202 -0
- pqlock-0.1.0.dist-info/licenses/NOTICE +8 -0
- pqlock-0.1.0.dist-info/top_level.txt +1 -0
pqlock/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""PQL post-quantum lock SDK for Python.
|
|
2
|
+
|
|
3
|
+
Every module is imported here once, by L00, so later loops only edit their own module folder.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from . import ( # noqa: F401
|
|
7
|
+
seal,
|
|
8
|
+
sign,
|
|
9
|
+
keyset,
|
|
10
|
+
policy,
|
|
11
|
+
tokens,
|
|
12
|
+
tls,
|
|
13
|
+
audit,
|
|
14
|
+
legacy,
|
|
15
|
+
stream,
|
|
16
|
+
rotate,
|
|
17
|
+
webhooks,
|
|
18
|
+
seal_batch,
|
|
19
|
+
)
|
|
20
|
+
from .errors import KeysetError, NotImplementedYet, OpenError, PolicyError, PQLError, VerifyError # noqa: F401
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"seal",
|
|
24
|
+
"sign",
|
|
25
|
+
"keyset",
|
|
26
|
+
"policy",
|
|
27
|
+
"tokens",
|
|
28
|
+
"tls",
|
|
29
|
+
"audit",
|
|
30
|
+
"legacy",
|
|
31
|
+
"stream",
|
|
32
|
+
"rotate",
|
|
33
|
+
"webhooks",
|
|
34
|
+
"seal_batch",
|
|
35
|
+
"KeysetError",
|
|
36
|
+
"NotImplementedYet",
|
|
37
|
+
"OpenError",
|
|
38
|
+
"PolicyError",
|
|
39
|
+
"PQLError",
|
|
40
|
+
"VerifyError",
|
|
41
|
+
]
|
pqlock/_suite.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
"""PQL suite compositions (spec/suites.md, spec/keyset.md). Internal: not part of the public API.
|
|
2
|
+
|
|
3
|
+
PQL never implements primitive math. Every primitive here comes from pyca/cryptography (OpenSSL):
|
|
4
|
+
ML-KEM-768/1024, ML-DSA-65/87, X25519, Ed25519, P-384 (ECDH, ECDSA), SHAKE256, SHA3-256, SHA-256,
|
|
5
|
+
SHA-384, SHA-512, HKDF-SHA256/384. This file only composes them, byte for byte as the spec says.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import binascii
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
from cryptography.exceptions import InvalidSignature
|
|
15
|
+
from cryptography.hazmat.primitives import hashes
|
|
16
|
+
from cryptography.hazmat.primitives.asymmetric import ec, ed25519, mldsa, mlkem, x25519
|
|
17
|
+
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature, encode_dss_signature
|
|
18
|
+
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
|
19
|
+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
20
|
+
|
|
21
|
+
# ---- identifiers -------------------------------------------------------------------------------
|
|
22
|
+
VERSION = 0x00
|
|
23
|
+
SUITE_DEFAULT = 0x0001
|
|
24
|
+
SUITE_HIGH = 0x0002
|
|
25
|
+
SUITE_CNSA = 0x0003
|
|
26
|
+
SUITE_LEGACY = 0x00FF
|
|
27
|
+
# Suites this SDK seals, signs, opens and verifies with (suites.md table). PQL-LEGACY is not one.
|
|
28
|
+
SUITE_NAMES = {"PQL-DEFAULT": SUITE_DEFAULT, "PQL-HIGH": SUITE_HIGH, "PQL-CNSA": SUITE_CNSA}
|
|
29
|
+
SUITE_IDS = frozenset(SUITE_NAMES.values())
|
|
30
|
+
# Token keys exist only for PQL-DEFAULT in v0.1 (suites.md, top).
|
|
31
|
+
TOKEN_SUITES = frozenset({SUITE_DEFAULT})
|
|
32
|
+
PURPOSES = {"seal": 0x01, "sign": 0x02, "token": 0x03}
|
|
33
|
+
KID_LEN = 8
|
|
34
|
+
KID_LABEL = b"PQL1 kid"
|
|
35
|
+
|
|
36
|
+
# ---- X-Wing (suites.md section 2) --------------------------------------------------------------
|
|
37
|
+
XWING_LABEL = bytes.fromhex("5c2e2f2f5e5c") # "\./" || "/^\"
|
|
38
|
+
XWING_SEED_LEN = 32
|
|
39
|
+
XWING_PK_LEN = 1216
|
|
40
|
+
XWING_CT_LEN = 1120
|
|
41
|
+
MLKEM_PK_LEN = 1184
|
|
42
|
+
MLKEM_CT_LEN = 1088
|
|
43
|
+
|
|
44
|
+
# ---- composite ML-DSA-65 + Ed25519 (suites.md section 3) ---------------------------------------
|
|
45
|
+
COMPOSITE_PREFIX = b"CompositeAlgorithmSignatures2025"
|
|
46
|
+
COMPOSITE_LABEL = b"COMPSIG-MLDSA65-Ed25519-SHA512"
|
|
47
|
+
COMPOSITE_SEED_LEN = 64
|
|
48
|
+
MLDSA65_SEED_LEN = 32
|
|
49
|
+
MLDSA65_PK_LEN = 1952
|
|
50
|
+
MLDSA65_SIG_LEN = 3309
|
|
51
|
+
ED25519_PK_LEN = 32
|
|
52
|
+
ED25519_SIG_LEN = 64
|
|
53
|
+
COMPOSITE_PK_LEN = MLDSA65_PK_LEN + ED25519_PK_LEN # 1984
|
|
54
|
+
COMPOSITE_SIG_LEN = MLDSA65_SIG_LEN + ED25519_SIG_LEN # 3373
|
|
55
|
+
|
|
56
|
+
# ---- PQL-HIGH / PQL-CNSA (suites.md sections 6-8) ------------------------------------------------
|
|
57
|
+
P384_N = int("ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973", 16)
|
|
58
|
+
P384_SK_LEN = 48
|
|
59
|
+
P384_PK_LEN = 97
|
|
60
|
+
P384_SIG_LEN = 96
|
|
61
|
+
MLKEM1024_SEED_LEN = 64
|
|
62
|
+
MLKEM1024_PK_LEN = 1568
|
|
63
|
+
MLKEM1024_CT_LEN = 1568
|
|
64
|
+
MLDSA87_SEED_LEN = 32
|
|
65
|
+
MLDSA87_PK_LEN = 2592
|
|
66
|
+
MLDSA87_SIG_LEN = 4627
|
|
67
|
+
HIGH_KEM_LABEL = b"PQL-HIGH MLKEM1024-P384"
|
|
68
|
+
COMPOSITE87_LABEL = b"COMPSIG-MLDSA87-ECDSA-P384-SHA512"
|
|
69
|
+
|
|
70
|
+
HIGH_SEAL_SECRET_LEN = MLKEM1024_SEED_LEN + P384_SK_LEN # 112
|
|
71
|
+
HIGH_SEAL_PK_LEN = MLKEM1024_PK_LEN + P384_PK_LEN # 1665
|
|
72
|
+
HIGH_KEM_CT_LEN = MLKEM1024_CT_LEN + P384_PK_LEN # 1665
|
|
73
|
+
HIGH_SIGN_SECRET_LEN = MLDSA87_SEED_LEN + P384_SK_LEN # 80
|
|
74
|
+
HIGH_SIGN_PK_LEN = MLDSA87_PK_LEN + P384_PK_LEN # 2689
|
|
75
|
+
HIGH_SIG_LEN = MLDSA87_SIG_LEN + P384_SIG_LEN # 4723
|
|
76
|
+
|
|
77
|
+
# Secret / public lengths per purpose for PQL-DEFAULT (keyset.md section 1).
|
|
78
|
+
SECRET_LEN = {"seal": XWING_SEED_LEN, "sign": COMPOSITE_SEED_LEN, "token": MLDSA65_SEED_LEN}
|
|
79
|
+
PUBLIC_LEN = {"seal": XWING_PK_LEN, "sign": COMPOSITE_PK_LEN, "token": MLDSA65_PK_LEN}
|
|
80
|
+
|
|
81
|
+
# Per-suite sizes (suites.md section 8). Token keys are PQL-DEFAULT only.
|
|
82
|
+
SIZES = {
|
|
83
|
+
SUITE_DEFAULT: {
|
|
84
|
+
"seal_secret": XWING_SEED_LEN, "seal_public": XWING_PK_LEN, "kem_ct": XWING_CT_LEN,
|
|
85
|
+
"sign_secret": COMPOSITE_SEED_LEN, "sign_public": COMPOSITE_PK_LEN, "sig_body": COMPOSITE_SIG_LEN,
|
|
86
|
+
},
|
|
87
|
+
SUITE_HIGH: {
|
|
88
|
+
"seal_secret": HIGH_SEAL_SECRET_LEN, "seal_public": HIGH_SEAL_PK_LEN, "kem_ct": HIGH_KEM_CT_LEN,
|
|
89
|
+
"sign_secret": HIGH_SIGN_SECRET_LEN, "sign_public": HIGH_SIGN_PK_LEN, "sig_body": HIGH_SIG_LEN,
|
|
90
|
+
},
|
|
91
|
+
SUITE_CNSA: {
|
|
92
|
+
"seal_secret": MLKEM1024_SEED_LEN, "seal_public": MLKEM1024_PK_LEN, "kem_ct": MLKEM1024_CT_LEN,
|
|
93
|
+
"sign_secret": MLDSA87_SEED_LEN, "sign_public": MLDSA87_PK_LEN, "sig_body": MLDSA87_SIG_LEN,
|
|
94
|
+
},
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _check_suite_purpose(suite: int, purpose: str) -> None:
|
|
99
|
+
if suite not in SUITE_IDS:
|
|
100
|
+
raise ValueError("unsupported suite")
|
|
101
|
+
if purpose == "token":
|
|
102
|
+
if suite not in TOKEN_SUITES:
|
|
103
|
+
raise ValueError("token keys are PQL-DEFAULT only")
|
|
104
|
+
elif purpose not in ("seal", "sign"):
|
|
105
|
+
raise ValueError("unknown purpose")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def secret_len(suite: int, purpose: str) -> int:
|
|
109
|
+
_check_suite_purpose(suite, purpose)
|
|
110
|
+
return SECRET_LEN["token"] if purpose == "token" else SIZES[suite][purpose + "_secret"]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def public_len(suite: int, purpose: str) -> int:
|
|
114
|
+
_check_suite_purpose(suite, purpose)
|
|
115
|
+
return PUBLIC_LEN["token"] if purpose == "token" else SIZES[suite][purpose + "_public"]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def kem_ct_len(suite: int) -> int:
|
|
119
|
+
return SIZES[suite]["kem_ct"]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def sig_body_len(suite: int) -> int:
|
|
123
|
+
return SIZES[suite]["sig_body"]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _digest(alg: hashes.HashAlgorithm, data: bytes) -> bytes:
|
|
127
|
+
h = hashes.Hash(alg)
|
|
128
|
+
h.update(data)
|
|
129
|
+
return h.finalize()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def sha256(data: bytes) -> bytes:
|
|
133
|
+
return _digest(hashes.SHA256(), data)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def sha512(data: bytes) -> bytes:
|
|
137
|
+
return _digest(hashes.SHA512(), data)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def sha3_256(data: bytes) -> bytes:
|
|
141
|
+
return _digest(hashes.SHA3_256(), data)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def shake256(data: bytes, n: int) -> bytes:
|
|
145
|
+
return _digest(hashes.SHAKE256(digest_size=n), data)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def sha384(data: bytes) -> bytes:
|
|
149
|
+
return _digest(hashes.SHA384(), data)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def hkdf_sha256(ikm: bytes, salt: bytes, info: bytes, length: int) -> bytes:
|
|
153
|
+
return HKDF(algorithm=hashes.SHA256(), length=length, salt=salt, info=info).derive(ikm)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def hkdf_sha384(ikm: bytes, salt: bytes, info: bytes, length: int) -> bytes:
|
|
157
|
+
return HKDF(algorithm=hashes.SHA384(), length=length, salt=salt, info=info).derive(ikm)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def header_hash(suite: int, header: bytes) -> bytes:
|
|
161
|
+
"""``th`` of the seal key schedule: SHA-256 for PQL-DEFAULT, SHA-384 for PQL-HIGH / PQL-CNSA."""
|
|
162
|
+
return sha256(header) if suite == SUITE_DEFAULT else sha384(header)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def seal_hkdf(suite: int, ikm: bytes, salt: bytes, info: bytes, length: int) -> bytes:
|
|
166
|
+
if suite == SUITE_DEFAULT:
|
|
167
|
+
return hkdf_sha256(ikm, salt, info, length)
|
|
168
|
+
if suite in (SUITE_HIGH, SUITE_CNSA):
|
|
169
|
+
return hkdf_sha384(ikm, salt, info, length)
|
|
170
|
+
raise ValueError("unsupported suite")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def u16(n: int) -> bytes:
|
|
174
|
+
return n.to_bytes(2, "big")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ---- key ids (keyset.md section 2) ---------------------------------------------------------------
|
|
178
|
+
def kid(suite: int, purpose: str, public: bytes) -> bytes:
|
|
179
|
+
return sha256(KID_LABEL + u16(suite) + bytes([PURPOSES[purpose]]) + public)[:KID_LEN]
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# ---- X-Wing ----------------------------------------------------------------------------------------
|
|
183
|
+
class XWingSecret:
|
|
184
|
+
"""Expanded X-Wing secret key. Holds engine key objects only, never prints the seed."""
|
|
185
|
+
|
|
186
|
+
__slots__ = ("sk_m", "sk_x", "pk_x", "public")
|
|
187
|
+
|
|
188
|
+
def __init__(self, seed: bytes) -> None:
|
|
189
|
+
if len(seed) != XWING_SEED_LEN:
|
|
190
|
+
raise ValueError("x-wing seed must be 32 bytes")
|
|
191
|
+
expanded = shake256(seed, 96)
|
|
192
|
+
self.sk_m = mlkem.MLKEM768PrivateKey.from_seed_bytes(expanded[0:64]) # d || z (FIPS 203)
|
|
193
|
+
self.sk_x = x25519.X25519PrivateKey.from_private_bytes(expanded[64:96])
|
|
194
|
+
self.pk_x = self.sk_x.public_key().public_bytes_raw()
|
|
195
|
+
self.public = self.sk_m.public_key().public_bytes_raw() + self.pk_x
|
|
196
|
+
|
|
197
|
+
def __repr__(self) -> str:
|
|
198
|
+
return "XWingSecret(<redacted>)"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def xwing_public(seed: bytes) -> bytes:
|
|
202
|
+
return XWingSecret(seed).public
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def xwing_combiner(ss_m: bytes, ss_x: bytes, ct_x: bytes, pk_x: bytes) -> bytes:
|
|
206
|
+
return sha3_256(ss_m + ss_x + ct_x + pk_x + XWING_LABEL)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def xwing_encaps(public: bytes) -> tuple[bytes, bytes]:
|
|
210
|
+
"""Returns (ciphertext, shared_secret). Randomness comes from the engine."""
|
|
211
|
+
if len(public) != XWING_PK_LEN:
|
|
212
|
+
raise ValueError("bad x-wing public key")
|
|
213
|
+
pk_m = mlkem.MLKEM768PublicKey.from_public_bytes(public[:MLKEM_PK_LEN])
|
|
214
|
+
pk_x = public[MLKEM_PK_LEN:]
|
|
215
|
+
ss_m, ct_m = pk_m.encapsulate()
|
|
216
|
+
ek_x = x25519.X25519PrivateKey.generate()
|
|
217
|
+
ct_x = ek_x.public_key().public_bytes_raw()
|
|
218
|
+
ss_x = ek_x.exchange(x25519.X25519PublicKey.from_public_bytes(pk_x))
|
|
219
|
+
return ct_m + ct_x, xwing_combiner(ss_m, ss_x, ct_x, pk_x)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def xwing_decaps(secret: XWingSecret, ciphertext: bytes) -> bytes:
|
|
223
|
+
if len(ciphertext) != XWING_CT_LEN:
|
|
224
|
+
raise ValueError("bad x-wing ciphertext")
|
|
225
|
+
ct_m, ct_x = ciphertext[:MLKEM_CT_LEN], ciphertext[MLKEM_CT_LEN:]
|
|
226
|
+
ss_m = secret.sk_m.decapsulate(ct_m) # implicit rejection
|
|
227
|
+
ss_x = secret.sk_x.exchange(x25519.X25519PublicKey.from_public_bytes(ct_x)) # raises on all-zero
|
|
228
|
+
return xwing_combiner(ss_m, ss_x, ct_x, secret.pk_x)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# ---- composite ML-DSA-65 + Ed25519 ---------------------------------------------------------------
|
|
232
|
+
class CompositeSecret:
|
|
233
|
+
__slots__ = ("sk_d", "sk_e", "public")
|
|
234
|
+
|
|
235
|
+
def __init__(self, seed: bytes) -> None:
|
|
236
|
+
if len(seed) != COMPOSITE_SEED_LEN:
|
|
237
|
+
raise ValueError("composite seed must be 64 bytes")
|
|
238
|
+
self.sk_d = mldsa.MLDSA65PrivateKey.from_seed_bytes(seed[:32])
|
|
239
|
+
self.sk_e = ed25519.Ed25519PrivateKey.from_private_bytes(seed[32:])
|
|
240
|
+
self.public = self.sk_d.public_key().public_bytes_raw() + self.sk_e.public_key().public_bytes_raw()
|
|
241
|
+
|
|
242
|
+
def __repr__(self) -> str:
|
|
243
|
+
return "CompositeSecret(<redacted>)"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def composite_public(seed: bytes) -> bytes:
|
|
247
|
+
return CompositeSecret(seed).public
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def composite_message(ctx: bytes, message: bytes) -> bytes:
|
|
251
|
+
if len(ctx) > 255:
|
|
252
|
+
raise ValueError("ctx too long")
|
|
253
|
+
return COMPOSITE_PREFIX + COMPOSITE_LABEL + bytes([len(ctx)]) + ctx + sha512(message)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def composite_sign(secret: CompositeSecret, ctx: bytes, message: bytes) -> bytes:
|
|
257
|
+
mp = composite_message(ctx, message)
|
|
258
|
+
return secret.sk_d.sign(mp, COMPOSITE_LABEL) + secret.sk_e.sign(mp)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def composite_verify(public: bytes, ctx: bytes, message: bytes, signature: bytes) -> bool:
|
|
262
|
+
"""True iff both halves verify. Both halves are always evaluated."""
|
|
263
|
+
if len(public) != COMPOSITE_PK_LEN or len(signature) != COMPOSITE_SIG_LEN:
|
|
264
|
+
return False
|
|
265
|
+
mp = composite_message(ctx, message)
|
|
266
|
+
pk_d = mldsa.MLDSA65PublicKey.from_public_bytes(public[:MLDSA65_PK_LEN])
|
|
267
|
+
pk_e = ed25519.Ed25519PublicKey.from_public_bytes(public[MLDSA65_PK_LEN:])
|
|
268
|
+
ok_d = ok_e = True
|
|
269
|
+
try:
|
|
270
|
+
pk_d.verify(signature[:MLDSA65_SIG_LEN], mp, COMPOSITE_LABEL)
|
|
271
|
+
except InvalidSignature:
|
|
272
|
+
ok_d = False
|
|
273
|
+
try:
|
|
274
|
+
pk_e.verify(signature[MLDSA65_SIG_LEN:], mp)
|
|
275
|
+
except InvalidSignature:
|
|
276
|
+
ok_e = False
|
|
277
|
+
return ok_d and ok_e
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# ---- ML-DSA-65 token keys (suites.md section 4) --------------------------------------------------
|
|
281
|
+
def mldsa65_secret(seed: bytes) -> mldsa.MLDSA65PrivateKey:
|
|
282
|
+
if len(seed) != MLDSA65_SEED_LEN:
|
|
283
|
+
raise ValueError("ml-dsa-65 seed must be 32 bytes")
|
|
284
|
+
return mldsa.MLDSA65PrivateKey.from_seed_bytes(seed)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def mldsa65_public(seed: bytes) -> bytes:
|
|
288
|
+
return mldsa65_secret(seed).public_key().public_bytes_raw()
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def mldsa65_verify(public: bytes, data: bytes, signature: bytes) -> bool:
|
|
292
|
+
if len(public) != MLDSA65_PK_LEN or len(signature) != MLDSA65_SIG_LEN:
|
|
293
|
+
return False
|
|
294
|
+
try:
|
|
295
|
+
mldsa.MLDSA65PublicKey.from_public_bytes(public).verify(signature, data)
|
|
296
|
+
except InvalidSignature:
|
|
297
|
+
return False
|
|
298
|
+
return True
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
# ---- P-384 encodings (suites.md section 6.1) -------------------------------------------------------
|
|
302
|
+
_P384 = ec.SECP384R1()
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def p384_private(scalar: bytes) -> ec.EllipticCurvePrivateKey:
|
|
306
|
+
"""A 48-byte big-endian scalar with 1 <= d < n, range-checked here before the engine sees it."""
|
|
307
|
+
if len(scalar) != P384_SK_LEN:
|
|
308
|
+
raise ValueError("p-384 scalar must be 48 bytes")
|
|
309
|
+
d = int.from_bytes(scalar, "big")
|
|
310
|
+
if not 1 <= d < P384_N:
|
|
311
|
+
raise ValueError("p-384 scalar out of range")
|
|
312
|
+
return ec.derive_private_key(d, _P384)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def p384_public(point: bytes) -> ec.EllipticCurvePublicKey:
|
|
316
|
+
"""A 97-byte SEC1 uncompressed point. Compressed (0x02/0x03) and hybrid (0x06/0x07) forms are
|
|
317
|
+
rejected here even though the engine would accept them; the engine checks the curve equation."""
|
|
318
|
+
if len(point) != P384_PK_LEN or point[0] != 0x04:
|
|
319
|
+
raise ValueError("p-384 point must be 97-byte uncompressed SEC1")
|
|
320
|
+
return ec.EllipticCurvePublicKey.from_encoded_point(_P384, point)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def p384_point_bytes(key: ec.EllipticCurvePublicKey) -> bytes:
|
|
324
|
+
return key.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
# ---- PQL-HIGH KEM: ML-KEM-1024 + P-384 (suites.md section 6.2) -----------------------------------
|
|
328
|
+
class HighKemSecret:
|
|
329
|
+
__slots__ = ("sk_m", "sk_e", "pk_e", "public")
|
|
330
|
+
|
|
331
|
+
def __init__(self, secret: bytes) -> None:
|
|
332
|
+
if len(secret) != HIGH_SEAL_SECRET_LEN:
|
|
333
|
+
raise ValueError("pql-high seal secret must be 112 bytes")
|
|
334
|
+
self.sk_m = mlkem.MLKEM1024PrivateKey.from_seed_bytes(secret[:MLKEM1024_SEED_LEN]) # d || z
|
|
335
|
+
self.sk_e = p384_private(secret[MLKEM1024_SEED_LEN:])
|
|
336
|
+
self.pk_e = p384_point_bytes(self.sk_e.public_key())
|
|
337
|
+
self.public = self.sk_m.public_key().public_bytes_raw() + self.pk_e
|
|
338
|
+
|
|
339
|
+
def __repr__(self) -> str:
|
|
340
|
+
return "HighKemSecret(<redacted>)"
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def high_combiner(ss_m: bytes, ss_e: bytes, ct_e: bytes, pk_e: bytes) -> bytes:
|
|
344
|
+
return sha3_256(ss_m + ss_e + ct_e + pk_e + HIGH_KEM_LABEL)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def high_encaps(public: bytes) -> tuple[bytes, bytes]:
|
|
348
|
+
if len(public) != HIGH_SEAL_PK_LEN:
|
|
349
|
+
raise ValueError("bad pql-high public key")
|
|
350
|
+
pk_m = mlkem.MLKEM1024PublicKey.from_public_bytes(public[:MLKEM1024_PK_LEN])
|
|
351
|
+
pk_e = public[MLKEM1024_PK_LEN:]
|
|
352
|
+
pk_e_key = p384_public(pk_e)
|
|
353
|
+
ss_m, ct_m = pk_m.encapsulate()
|
|
354
|
+
eph = ec.generate_private_key(_P384)
|
|
355
|
+
ct_e = p384_point_bytes(eph.public_key())
|
|
356
|
+
ss_e = eph.exchange(ec.ECDH(), pk_e_key) # x-coordinate, 48 bytes
|
|
357
|
+
return ct_m + ct_e, high_combiner(ss_m, ss_e, ct_e, pk_e)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def high_decaps(secret: HighKemSecret, ciphertext: bytes) -> bytes:
|
|
361
|
+
if len(ciphertext) != HIGH_KEM_CT_LEN:
|
|
362
|
+
raise ValueError("bad pql-high kem ciphertext")
|
|
363
|
+
ct_m, ct_e = ciphertext[:MLKEM1024_CT_LEN], ciphertext[MLKEM1024_CT_LEN:]
|
|
364
|
+
ss_m = secret.sk_m.decapsulate(ct_m) # implicit rejection
|
|
365
|
+
ss_e = secret.sk_e.exchange(ec.ECDH(), p384_public(ct_e))
|
|
366
|
+
return high_combiner(ss_m, ss_e, ct_e, secret.pk_e)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
# ---- PQL-CNSA KEM: ML-KEM-1024 (suites.md section 7.1) --------------------------------------------
|
|
370
|
+
def cnsa_kem_secret(secret: bytes) -> mlkem.MLKEM1024PrivateKey:
|
|
371
|
+
if len(secret) != MLKEM1024_SEED_LEN:
|
|
372
|
+
raise ValueError("pql-cnsa seal secret must be 64 bytes")
|
|
373
|
+
return mlkem.MLKEM1024PrivateKey.from_seed_bytes(secret)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def cnsa_encaps(public: bytes) -> tuple[bytes, bytes]:
|
|
377
|
+
if len(public) != MLKEM1024_PK_LEN:
|
|
378
|
+
raise ValueError("bad pql-cnsa public key")
|
|
379
|
+
ss, ct = mlkem.MLKEM1024PublicKey.from_public_bytes(public).encapsulate()
|
|
380
|
+
return ct, ss
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def cnsa_decaps(secret: mlkem.MLKEM1024PrivateKey, ciphertext: bytes) -> bytes:
|
|
384
|
+
if len(ciphertext) != MLKEM1024_CT_LEN:
|
|
385
|
+
raise ValueError("bad pql-cnsa kem ciphertext")
|
|
386
|
+
return secret.decapsulate(ciphertext)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
# ---- suite-generic KEM ---------------------------------------------------------------------------
|
|
390
|
+
def kem_encaps(suite: int, public: bytes) -> tuple[bytes, bytes]:
|
|
391
|
+
"""Returns (kem_ciphertext, shared_secret) for the suite."""
|
|
392
|
+
if suite == SUITE_DEFAULT:
|
|
393
|
+
return xwing_encaps(public)
|
|
394
|
+
if suite == SUITE_HIGH:
|
|
395
|
+
return high_encaps(public)
|
|
396
|
+
if suite == SUITE_CNSA:
|
|
397
|
+
return cnsa_encaps(public)
|
|
398
|
+
raise ValueError("unsupported suite")
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def kem_decaps(suite: int, secret: bytes, ciphertext: bytes) -> bytes:
|
|
402
|
+
if suite == SUITE_DEFAULT:
|
|
403
|
+
return xwing_decaps(XWingSecret(secret), ciphertext)
|
|
404
|
+
if suite == SUITE_HIGH:
|
|
405
|
+
return high_decaps(HighKemSecret(secret), ciphertext)
|
|
406
|
+
if suite == SUITE_CNSA:
|
|
407
|
+
return cnsa_decaps(cnsa_kem_secret(secret), ciphertext)
|
|
408
|
+
raise ValueError("unsupported suite")
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
# ---- PQL-HIGH sign: composite ML-DSA-87 + ECDSA-P384-SHA512 (suites.md section 6.3) -------------
|
|
412
|
+
class Composite87Secret:
|
|
413
|
+
__slots__ = ("sk_d", "sk_e", "public")
|
|
414
|
+
|
|
415
|
+
def __init__(self, secret: bytes) -> None:
|
|
416
|
+
if len(secret) != HIGH_SIGN_SECRET_LEN:
|
|
417
|
+
raise ValueError("pql-high sign secret must be 80 bytes")
|
|
418
|
+
self.sk_d = mldsa.MLDSA87PrivateKey.from_seed_bytes(secret[:MLDSA87_SEED_LEN])
|
|
419
|
+
self.sk_e = p384_private(secret[MLDSA87_SEED_LEN:])
|
|
420
|
+
self.public = self.sk_d.public_key().public_bytes_raw() + p384_point_bytes(self.sk_e.public_key())
|
|
421
|
+
|
|
422
|
+
def __repr__(self) -> str:
|
|
423
|
+
return "Composite87Secret(<redacted>)"
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def composite87_message(ctx: bytes, message: bytes) -> bytes:
|
|
427
|
+
if len(ctx) > 255:
|
|
428
|
+
raise ValueError("ctx too long")
|
|
429
|
+
return COMPOSITE_PREFIX + COMPOSITE87_LABEL + bytes([len(ctx)]) + ctx + sha512(message)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def composite87_sign(secret: Composite87Secret, ctx: bytes, message: bytes) -> bytes:
|
|
433
|
+
mp = composite87_message(ctx, message)
|
|
434
|
+
sig_d = secret.sk_d.sign(mp, COMPOSITE87_LABEL)
|
|
435
|
+
r, s = decode_dss_signature(secret.sk_e.sign(mp, ec.ECDSA(hashes.SHA512())))
|
|
436
|
+
return sig_d + r.to_bytes(P384_SK_LEN, "big") + s.to_bytes(P384_SK_LEN, "big")
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _p384_verify_p1363(pk: ec.EllipticCurvePublicKey, sig: bytes, data: bytes) -> bool:
|
|
440
|
+
"""ECDSA-P384-SHA512 over ``data`` with an IEEE P1363 ``r || s`` signature. r and s outside
|
|
441
|
+
[1, n) are a failed verification, never an exception."""
|
|
442
|
+
if len(sig) != P384_SIG_LEN:
|
|
443
|
+
return False
|
|
444
|
+
r = int.from_bytes(sig[:P384_SK_LEN], "big")
|
|
445
|
+
s = int.from_bytes(sig[P384_SK_LEN:], "big")
|
|
446
|
+
if not (1 <= r < P384_N and 1 <= s < P384_N):
|
|
447
|
+
return False
|
|
448
|
+
try:
|
|
449
|
+
pk.verify(encode_dss_signature(r, s), data, ec.ECDSA(hashes.SHA512()))
|
|
450
|
+
except InvalidSignature:
|
|
451
|
+
return False
|
|
452
|
+
return True
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def composite87_verify(public: bytes, ctx: bytes, message: bytes, signature: bytes) -> bool:
|
|
456
|
+
"""True iff both halves verify. Both halves are always evaluated."""
|
|
457
|
+
if len(public) != HIGH_SIGN_PK_LEN or len(signature) != HIGH_SIG_LEN:
|
|
458
|
+
return False
|
|
459
|
+
mp = composite87_message(ctx, message)
|
|
460
|
+
pk_d = mldsa.MLDSA87PublicKey.from_public_bytes(public[:MLDSA87_PK_LEN])
|
|
461
|
+
pk_e = p384_public(public[MLDSA87_PK_LEN:])
|
|
462
|
+
ok_d = True
|
|
463
|
+
try:
|
|
464
|
+
pk_d.verify(signature[:MLDSA87_SIG_LEN], mp, COMPOSITE87_LABEL)
|
|
465
|
+
except InvalidSignature:
|
|
466
|
+
ok_d = False
|
|
467
|
+
ok_e = _p384_verify_p1363(pk_e, signature[MLDSA87_SIG_LEN:], mp)
|
|
468
|
+
return ok_d and ok_e
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
# ---- PQL-CNSA sign: ML-DSA-87 (suites.md section 7.2) ---------------------------------------------
|
|
472
|
+
def mldsa87_secret(seed: bytes) -> mldsa.MLDSA87PrivateKey:
|
|
473
|
+
if len(seed) != MLDSA87_SEED_LEN:
|
|
474
|
+
raise ValueError("ml-dsa-87 seed must be 32 bytes")
|
|
475
|
+
return mldsa.MLDSA87PrivateKey.from_seed_bytes(seed)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def mldsa87_verify(public: bytes, ctx: bytes, message: bytes, signature: bytes) -> bool:
|
|
479
|
+
if len(public) != MLDSA87_PK_LEN or len(signature) != MLDSA87_SIG_LEN:
|
|
480
|
+
return False
|
|
481
|
+
try:
|
|
482
|
+
mldsa.MLDSA87PublicKey.from_public_bytes(public).verify(signature, message, ctx)
|
|
483
|
+
except InvalidSignature:
|
|
484
|
+
return False
|
|
485
|
+
return True
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
# ---- suite-generic sign / verify (ctx is always the 15-byte sig_header) ---------------------------
|
|
489
|
+
def sign_body(suite: int, secret: bytes, ctx: bytes, message: bytes) -> bytes:
|
|
490
|
+
if suite == SUITE_DEFAULT:
|
|
491
|
+
return composite_sign(CompositeSecret(secret), ctx, message)
|
|
492
|
+
if suite == SUITE_HIGH:
|
|
493
|
+
return composite87_sign(Composite87Secret(secret), ctx, message)
|
|
494
|
+
if suite == SUITE_CNSA:
|
|
495
|
+
return mldsa87_secret(secret).sign(message, ctx)
|
|
496
|
+
raise ValueError("unsupported suite")
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def verify_body(suite: int, public: bytes, ctx: bytes, message: bytes, body: bytes) -> bool:
|
|
500
|
+
if suite == SUITE_DEFAULT:
|
|
501
|
+
return composite_verify(public, ctx, message, body)
|
|
502
|
+
if suite == SUITE_HIGH:
|
|
503
|
+
return composite87_verify(public, ctx, message, body)
|
|
504
|
+
if suite == SUITE_CNSA:
|
|
505
|
+
return mldsa87_verify(public, ctx, message, body)
|
|
506
|
+
return False
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
# ---- keys -----------------------------------------------------------------------------------------
|
|
510
|
+
def public_from_secret(purpose: str, secret: bytes, suite: int = SUITE_DEFAULT) -> bytes:
|
|
511
|
+
"""Derive the public key. Raises ValueError for a bad secret or an unsupported suite/purpose."""
|
|
512
|
+
_check_suite_purpose(suite, purpose)
|
|
513
|
+
if purpose == "token":
|
|
514
|
+
return mldsa65_public(secret)
|
|
515
|
+
if suite == SUITE_DEFAULT:
|
|
516
|
+
return xwing_public(secret) if purpose == "seal" else composite_public(secret)
|
|
517
|
+
if suite == SUITE_HIGH:
|
|
518
|
+
return HighKemSecret(secret).public if purpose == "seal" else Composite87Secret(secret).public
|
|
519
|
+
if purpose == "seal":
|
|
520
|
+
return cnsa_kem_secret(secret).public_key().public_bytes_raw()
|
|
521
|
+
return mldsa87_secret(secret).public_key().public_bytes_raw()
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def check_public(suite: int, purpose: str, public: bytes) -> None:
|
|
525
|
+
"""Structural check of a PQL-HIGH / PQL-CNSA public key through the engine (lengths, the P-384
|
|
526
|
+
point encoding and curve membership, ML-KEM / ML-DSA key import). Raises ValueError.
|
|
527
|
+
PQL-DEFAULT public keys are checked only by length, as in v0."""
|
|
528
|
+
if len(public) != public_len(suite, purpose):
|
|
529
|
+
raise ValueError("public key has the wrong length")
|
|
530
|
+
if suite == SUITE_HIGH:
|
|
531
|
+
if purpose == "seal":
|
|
532
|
+
mlkem.MLKEM1024PublicKey.from_public_bytes(public[:MLKEM1024_PK_LEN])
|
|
533
|
+
p384_public(public[MLKEM1024_PK_LEN:])
|
|
534
|
+
else:
|
|
535
|
+
mldsa.MLDSA87PublicKey.from_public_bytes(public[:MLDSA87_PK_LEN])
|
|
536
|
+
p384_public(public[MLDSA87_PK_LEN:])
|
|
537
|
+
elif suite == SUITE_CNSA:
|
|
538
|
+
if purpose == "seal":
|
|
539
|
+
mlkem.MLKEM1024PublicKey.from_public_bytes(public)
|
|
540
|
+
else:
|
|
541
|
+
mldsa.MLDSA87PublicKey.from_public_bytes(public)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
# ---- base64url (envelope.md section 4) -------------------------------------------------------------
|
|
545
|
+
_B64U = re.compile(r"[A-Za-z0-9_-]*")
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def b64u(data: bytes) -> str:
|
|
549
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def from_b64u(text: str) -> bytes:
|
|
553
|
+
"""Strict unpadded base64url: right alphabet, no padding or whitespace, canonical trailing bits."""
|
|
554
|
+
if not isinstance(text, str) or not _B64U.fullmatch(text) or len(text) % 4 == 1:
|
|
555
|
+
raise ValueError("bad base64url")
|
|
556
|
+
try:
|
|
557
|
+
out = base64.b64decode(text + "=" * (-len(text) % 4), altchars=b"-_", validate=True)
|
|
558
|
+
except (binascii.Error, ValueError):
|
|
559
|
+
raise ValueError("bad base64url") from None
|
|
560
|
+
if b64u(out) != text:
|
|
561
|
+
raise ValueError("non-canonical base64url")
|
|
562
|
+
return out
|