-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathwycheproof_client.py
More file actions
282 lines (248 loc) · 9.67 KB
/
wycheproof_client.py
File metadata and controls
282 lines (248 loc) · 9.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env python3
# Copyright (c) The mlkem-native project authors
# SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT
# Wycheproof test client for ML-KEM
# See https://github.com/C2SP/wycheproof
# Invokes `wycheproof_mlkem{lvl}` under the hood.
import argparse
import os
import json
import sys
import subprocess
import urllib.request
from pathlib import Path
exec_prefix = os.environ.get("EXEC_WRAPPER", "")
exec_prefix = exec_prefix.split(" ") if exec_prefix != "" else []
WYCHEPROOF_BASE_URL = (
"https://raw.githubusercontent.com/C2SP/wycheproof/main/testvectors_v1"
)
WYCHEPROOF_FILES = [
"mlkem_512_keygen_seed_test.json",
"mlkem_512_encaps_test.json",
"mlkem_512_semi_expanded_decaps_test.json",
"mlkem_512_test.json",
"mlkem_768_keygen_seed_test.json",
"mlkem_768_encaps_test.json",
"mlkem_768_semi_expanded_decaps_test.json",
"mlkem_768_test.json",
"mlkem_1024_keygen_seed_test.json",
"mlkem_1024_encaps_test.json",
"mlkem_1024_semi_expanded_decaps_test.json",
"mlkem_1024_test.json",
]
PARAMETER_SET_TO_LEVEL = {
"ML-KEM-512": 512,
"ML-KEM-768": 768,
"ML-KEM-1024": 1024,
}
def err(msg, **kwargs):
print(msg, file=sys.stderr, **kwargs)
def info(msg, **kwargs):
print(msg, **kwargs)
def download_wycheproof_files(data_dir):
"""Download Wycheproof test vector files if not present."""
data_dir = Path(data_dir)
data_dir.mkdir(parents=True, exist_ok=True)
for filename in WYCHEPROOF_FILES:
local_file = data_dir / filename
if not local_file.exists():
url = f"{WYCHEPROOF_BASE_URL}/{filename}"
print(f"Downloading {filename}...", file=sys.stderr)
try:
urllib.request.urlretrieve(url, local_file)
with open(local_file, "r", encoding="utf-8") as f:
json.load(f)
except (json.JSONDecodeError, Exception) as e:
print(f"Error downloading {filename}: {e}", file=sys.stderr)
local_file.unlink(missing_ok=True)
return False
return True
def get_binary(level):
basedir = f"./test/build/mlkem{level}/bin"
return f"{basedir}/wycheproof_mlkem{level}"
def run_binary(args_list):
result = subprocess.run(
exec_prefix + args_list, encoding="utf-8", capture_output=True
)
if result.returncode != 0:
return {"_error": str(result.returncode)}
out = {}
for line in result.stdout.strip().splitlines():
k, v = line.split("=", 1)
out[k] = v
return out
def run_keygen_seed_test(data_file):
"""Run mlkem_*_keygen_seed_test.json tests."""
with open(data_file, "r", encoding="utf-8") as f:
data = json.load(f)
info(f"Running keygen_seed tests from {data_file}")
count = 0
for tg in data["testGroups"]:
level = PARAMETER_SET_TO_LEVEL[tg["parameterSet"]]
binary = get_binary(level)
for tc in tg["tests"]:
info(f" tcId={tc['tcId']} ... ", end="")
out = run_binary([binary, "keygen_seed", f"seed={tc['seed']}"])
if tc["result"] == "valid":
assert out["ek"].upper() == tc["ek"].upper(), (
f"ek mismatch tcId={tc['tcId']}"
)
assert out["dk"].upper() == tc["dk"].upper(), (
f"dk mismatch tcId={tc['tcId']}"
)
else:
assert False, (
f"Unexpected result '{tc['result']}' for tcId={tc['tcId']}"
)
info("ok")
count += 1
info(f" {count} keygen_seed tests passed")
def run_encaps_test(data_file):
"""Run mlkem_*_encaps_test.json tests."""
with open(data_file, "r", encoding="utf-8") as f:
data = json.load(f)
info(f"Running encaps tests from {data_file}")
count = 0
for tg in data["testGroups"]:
level = PARAMETER_SET_TO_LEVEL[tg["parameterSet"]]
binary = get_binary(level)
for tc in tg["tests"]:
info(f" tcId={tc['tcId']} ... ", end="")
out = run_binary([binary, "encaps", f"ek={tc['ek']}", f"m={tc['m']}"])
if tc["result"] == "invalid":
# _error: non-zero exit code; decode_error: explicit validation failure
assert "_error" in out or "decode_error" in out, (
f"binary success on invalid tcId={tc['tcId']}"
)
elif tc["result"] == "valid":
assert out["c"].upper() == tc["c"].upper(), (
f"c mismatch tcId={tc['tcId']}"
)
assert out["K"].upper() == tc["K"].upper(), (
f"K mismatch tcId={tc['tcId']}"
)
else:
assert False, (
f"Unsupported test result '{tc['result']}' for tcId={tc['tcId']}"
)
info("ok")
count += 1
info(f" {count} encaps tests passed")
def run_semi_expanded_decaps_test(data_file):
"""Run mlkem_*_semi_expanded_decaps_test.json tests."""
with open(data_file, "r", encoding="utf-8") as f:
data = json.load(f)
info(f"Running semi_expanded_decaps tests from {data_file}")
count = 0
for tg in data["testGroups"]:
level = PARAMETER_SET_TO_LEVEL[tg["parameterSet"]]
binary = get_binary(level)
for tc in tg["tests"]:
info(f" tcId={tc['tcId']} ... ", end="")
out = run_binary([binary, "decaps", f"dk={tc['dk']}", f"c={tc['c']}"])
if tc["result"] == "invalid":
# _error: non-zero exit code; decode_error: explicit validation failure
assert "_error" in out or "decode_error" in out, (
f"binary success on invalid tcId={tc['tcId']}"
)
elif tc["result"] == "valid":
assert "K" in out, f"missing K in output tcId={tc['tcId']}"
else:
assert False, (
f"Unsupported test result '{tc['result']}' for tcId={tc['tcId']}"
)
info("ok")
count += 1
info(f" {count} semi_expanded_decaps tests passed")
def run_combined_test(data_file):
"""Run mlkem_*_test.json tests (keygen + decaps)."""
with open(data_file, "r", encoding="utf-8") as f:
data = json.load(f)
info(f"Running combined (keygen+decaps) tests from {data_file}")
count = 0
for tg in data["testGroups"]:
level = PARAMETER_SET_TO_LEVEL[tg["parameterSet"]]
binary = get_binary(level)
for tc in tg["tests"]:
info(f" tcId={tc['tcId']} ... ", end="")
# Generate keypair from seed
keygen_out = run_binary([binary, "keygen_seed", f"seed={tc['seed']}"])
if "decode_error" in keygen_out:
assert tc["result"] == "invalid", (
f"keygen decode error on valid tcId={tc['tcId']}"
)
info("ok")
count += 1
continue
# Keygen succeeded — check ek
assert "ek" in tc, f"missing ek in test vector tcId={tc['tcId']}"
assert keygen_out["ek"].upper() == tc["ek"].upper(), (
f"ek mismatch tcId={tc['tcId']}"
)
# Decapsulate
dk = keygen_out["dk"]
decaps_out = run_binary([binary, "decaps", f"dk={dk}", f"c={tc['c']}"])
if tc["result"] == "invalid":
# _error: non-zero exit code; decode_error: explicit validation failure
assert "_error" in decaps_out or "decode_error" in decaps_out, (
f"binary success on invalid tcId={tc['tcId']}"
)
elif tc["result"] == "valid":
assert decaps_out["K"].upper() == tc["K"].upper(), (
f"K mismatch tcId={tc['tcId']}"
)
else:
assert False, (
f"Unsupported test result '{tc['result']}' for tcId={tc['tcId']}"
)
info("ok")
count += 1
info(f" {count} combined tests passed")
def run_all(data_dir):
"""Run all Wycheproof test vector files."""
data_dir = Path(data_dir)
for filename in WYCHEPROOF_FILES:
filepath = data_dir / filename
if "keygen_seed_test" in filename:
run_keygen_seed_test(filepath)
elif "encaps_test" in filename:
run_encaps_test(filepath)
elif "semi_expanded_decaps_test" in filename:
run_semi_expanded_decaps_test(filepath)
elif filename.endswith("_test.json"):
run_combined_test(filepath)
info("ALL GOOD!")
parser = argparse.ArgumentParser(description="Wycheproof ML-KEM test client")
parser.add_argument(
"-f",
"--file",
help="Path to a specific Wycheproof test vector JSON file",
required=False,
)
parser.add_argument(
"--data-dir",
default="test/wycheproof/.wycheproof-data",
help="Directory for downloaded test vectors (default: test/wycheproof/.wycheproof-data)",
)
args = parser.parse_args()
if args.file:
# Run a single file
filename = os.path.basename(args.file)
if "keygen_seed_test" in filename:
run_keygen_seed_test(args.file)
elif "encaps_test" in filename:
run_encaps_test(args.file)
elif "semi_expanded_decaps_test" in filename:
run_semi_expanded_decaps_test(args.file)
elif filename.endswith("_test.json"):
run_combined_test(args.file)
else:
err(f"Unknown test file type: {filename}")
sys.exit(1)
info("ALL GOOD!")
else:
# Download and run all
if not download_wycheproof_files(args.data_dir):
err("Failed to download Wycheproof test files")
sys.exit(1)
run_all(args.data_dir)