| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
import argparse |
| 12 |
import hashlib |
| 13 |
import os |
| 14 |
import json |
| 15 |
import sys |
| 16 |
import subprocess |
| 17 |
import urllib.request |
| 18 |
from pathlib import Path |
| 19 |
|
| 20 |
|
| 21 |
exec_prefix = os.environ.get("EXEC_WRAPPER", "") |
| 22 |
exec_prefix = exec_prefix.split(" ") if exec_prefix != "" else [] |
| 23 |
|
| 24 |
|
| 25 |
def download_acvp_files(version): |
| 26 |
"""Download ACVP test files for the specified version if not present.""" |
| 27 |
base_url = f"https://raw.githubusercontent.com/usnistgov/ACVP-Server/{version}/gen-val/json-files" |
| 28 |
|
| 29 |
|
| 30 |
files_to_download = [ |
| 31 |
"ML-DSA-keyGen-FIPS204/prompt.json", |
| 32 |
"ML-DSA-keyGen-FIPS204/expectedResults.json", |
| 33 |
"ML-DSA-sigGen-FIPS204/prompt.json", |
| 34 |
"ML-DSA-sigGen-FIPS204/expectedResults.json", |
| 35 |
"ML-DSA-sigVer-FIPS204/prompt.json", |
| 36 |
"ML-DSA-sigVer-FIPS204/expectedResults.json", |
| 37 |
] |
| 38 |
|
| 39 |
|
| 40 |
data_dir = Path(f"test/acvp/.acvp-data/{version}/files") |
| 41 |
data_dir.mkdir(parents=True, exist_ok=True) |
| 42 |
|
| 43 |
for file_path in files_to_download: |
| 44 |
local_file = data_dir / file_path |
| 45 |
local_file.parent.mkdir(parents=True, exist_ok=True) |
| 46 |
|
| 47 |
if not local_file.exists(): |
| 48 |
url = f"{base_url}/{file_path}" |
| 49 |
print(f"Downloading {file_path}...", file=sys.stderr) |
| 50 |
try: |
| 51 |
urllib.request.urlretrieve(url, local_file) |
| 52 |
|
| 53 |
with open(local_file, "r") as f: |
| 54 |
json.load(f) |
| 55 |
except json.JSONDecodeError as e: |
| 56 |
print( |
| 57 |
f"Error: Downloaded file {file_path} is not valid JSON: {e}", |
| 58 |
file=sys.stderr, |
| 59 |
) |
| 60 |
local_file.unlink(missing_ok=True) |
| 61 |
return False |
| 62 |
except Exception as e: |
| 63 |
print(f"Error downloading {file_path}: {e}", file=sys.stderr) |
| 64 |
local_file.unlink(missing_ok=True) |
| 65 |
return False |
| 66 |
|
| 67 |
return True |
| 68 |
|
| 69 |
|
| 70 |
def loadAcvpData(prompt, expectedResults): |
| 71 |
with open(prompt, "r") as f: |
| 72 |
promptData = json.load(f) |
| 73 |
expectedResultsData = None |
| 74 |
if expectedResults is not None: |
| 75 |
with open(expectedResults, "r") as f: |
| 76 |
expectedResultsData = json.load(f) |
| 77 |
|
| 78 |
return (prompt, promptData, expectedResults, expectedResultsData) |
| 79 |
|
| 80 |
|
| 81 |
def loadDefaultAcvpData(version): |
| 82 |
data_dir = f"test/acvp/.acvp-data/{version}/files" |
| 83 |
acvp_jsons_for_version = [ |
| 84 |
( |
| 85 |
f"{data_dir}/ML-DSA-keyGen-FIPS204/prompt.json", |
| 86 |
f"{data_dir}/ML-DSA-keyGen-FIPS204/expectedResults.json", |
| 87 |
), |
| 88 |
( |
| 89 |
f"{data_dir}/ML-DSA-sigGen-FIPS204/prompt.json", |
| 90 |
f"{data_dir}/ML-DSA-sigGen-FIPS204/expectedResults.json", |
| 91 |
), |
| 92 |
( |
| 93 |
f"{data_dir}/ML-DSA-sigVer-FIPS204/prompt.json", |
| 94 |
f"{data_dir}/ML-DSA-sigVer-FIPS204/expectedResults.json", |
| 95 |
), |
| 96 |
] |
| 97 |
acvp_data = [] |
| 98 |
for prompt, expectedResults in acvp_jsons_for_version: |
| 99 |
acvp_data.append(loadAcvpData(prompt, expectedResults)) |
| 100 |
return acvp_data |
| 101 |
|
| 102 |
|
| 103 |
def err(msg, **kwargs): |
| 104 |
print(msg, file=sys.stderr, **kwargs) |
| 105 |
|
| 106 |
|
| 107 |
def info(msg, **kwargs): |
| 108 |
print(msg, **kwargs) |
| 109 |
|
| 110 |
|
| 111 |
def get_acvp_binary(tg): |
| 112 |
"""Convert JSON dict for ACVP test group to suitable ACVP binary.""" |
| 113 |
parameterSetToLevel = { |
| 114 |
"ML-DSA-44": 44, |
| 115 |
"ML-DSA-65": 65, |
| 116 |
"ML-DSA-87": 87, |
| 117 |
} |
| 118 |
level = parameterSetToLevel[tg["parameterSet"]] |
| 119 |
basedir = f"./test/build/mldsa{level}/bin" |
| 120 |
acvp_bin = f"acvp_mldsa{level}" |
| 121 |
return f"{basedir}/{acvp_bin}" |
| 122 |
|
| 123 |
|
| 124 |
def run_keyGen_test(tg, tc): |
| 125 |
info(f"Running keyGen test case {tc['tcId']} ... ", end="") |
| 126 |
|
| 127 |
results = {"tcId": tc["tcId"]} |
| 128 |
acvp_bin = get_acvp_binary(tg) |
| 129 |
assert tg["testType"] == "AFT" |
| 130 |
acvp_call = exec_prefix + [ |
| 131 |
acvp_bin, |
| 132 |
"keyGen", |
| 133 |
f"seed={tc['seed']}", |
| 134 |
] |
| 135 |
result = subprocess.run(acvp_call, encoding="utf-8", capture_output=True) |
| 136 |
if result.returncode != 0: |
| 137 |
err("FAIL!") |
| 138 |
err(f"{acvp_call} failed with error code {result.returncode}") |
| 139 |
err(result.stderr) |
| 140 |
exit(1) |
| 141 |
|
| 142 |
for l in result.stdout.splitlines(): |
| 143 |
(k, v) = l.split("=") |
| 144 |
results[k] = v |
| 145 |
info("done") |
| 146 |
return results |
| 147 |
|
| 148 |
|
| 149 |
def compute_hash(msg, alg): |
| 150 |
msg_bytes = bytes.fromhex(msg) |
| 151 |
|
| 152 |
if alg == "SHA2-224": |
| 153 |
return hashlib.sha224(msg_bytes).hexdigest() |
| 154 |
elif alg == "SHA2-256": |
| 155 |
return hashlib.sha256(msg_bytes).hexdigest() |
| 156 |
elif alg == "SHA2-384": |
| 157 |
return hashlib.sha384(msg_bytes).hexdigest() |
| 158 |
elif alg == "SHA2-512": |
| 159 |
return hashlib.sha512(msg_bytes).hexdigest() |
| 160 |
elif alg == "SHA2-512/224": |
| 161 |
return hashlib.new("sha512_224", msg_bytes).hexdigest() |
| 162 |
elif alg == "SHA2-512/256": |
| 163 |
return hashlib.new("sha512_256", msg_bytes).hexdigest() |
| 164 |
elif alg == "SHA3-224": |
| 165 |
return hashlib.sha3_224(msg_bytes).hexdigest() |
| 166 |
elif alg == "SHA3-256": |
| 167 |
return hashlib.sha3_256(msg_bytes).hexdigest() |
| 168 |
elif alg == "SHA3-384": |
| 169 |
return hashlib.sha3_384(msg_bytes).hexdigest() |
| 170 |
elif alg == "SHA3-512": |
| 171 |
return hashlib.sha3_512(msg_bytes).hexdigest() |
| 172 |
elif alg == "SHAKE-128": |
| 173 |
return hashlib.shake_128(msg_bytes).hexdigest(32) |
| 174 |
elif alg == "SHAKE-256": |
| 175 |
return hashlib.shake_256(msg_bytes).hexdigest(64) |
| 176 |
else: |
| 177 |
raise ValueError(f"Unsupported hash algorithm: {alg}") |
| 178 |
|
| 179 |
|
| 180 |
def run_sigGen_test(tg, tc): |
| 181 |
info(f"Running sigGen test case {tc['tcId']} ... ", end="") |
| 182 |
results = {"tcId": tc["tcId"]} |
| 183 |
acvp_bin = get_acvp_binary(tg) |
| 184 |
|
| 185 |
assert tg["testType"] == "AFT" |
| 186 |
|
| 187 |
is_deterministic = tg["deterministic"] is True |
| 188 |
if "preHash" in tg and tg["preHash"] == "preHash": |
| 189 |
assert len(tc["context"]) <= 2 * 255 |
| 190 |
|
| 191 |
|
| 192 |
if tc["hashAlg"] == "SHAKE-256": |
| 193 |
target = ( |
| 194 |
"sigGenPreHashShake256Deterministic" |
| 195 |
if is_deterministic |
| 196 |
else "sigGenPreHashShake256" |
| 197 |
) |
| 198 |
acvp_call = exec_prefix + [ |
| 199 |
acvp_bin, |
| 200 |
target, |
| 201 |
f"message={tc['message']}", |
| 202 |
f"context={tc['context']}", |
| 203 |
f"sk={tc['sk']}", |
| 204 |
] |
| 205 |
else: |
| 206 |
ph = compute_hash(tc["message"], tc["hashAlg"]) |
| 207 |
target = ( |
| 208 |
"sigGenPreHashDeterministic" if is_deterministic else "sigGenPreHash" |
| 209 |
) |
| 210 |
acvp_call = exec_prefix + [ |
| 211 |
acvp_bin, |
| 212 |
target, |
| 213 |
f"ph={ph}", |
| 214 |
f"context={tc['context']}", |
| 215 |
f"sk={tc['sk']}", |
| 216 |
f"hashAlg={tc['hashAlg']}", |
| 217 |
] |
| 218 |
elif tg["signatureInterface"] == "external": |
| 219 |
assert "hashAlg" not in tc or tc["hashAlg"] == "none" |
| 220 |
assert len(tc["context"]) <= 2 * 255 |
| 221 |
assert len(tc["message"]) <= 2 * 65536 |
| 222 |
|
| 223 |
target = "sigGenDeterministic" if is_deterministic else "sigGen" |
| 224 |
acvp_call = exec_prefix + [ |
| 225 |
acvp_bin, |
| 226 |
target, |
| 227 |
f"message={tc['message']}", |
| 228 |
f"sk={tc['sk']}", |
| 229 |
f"context={tc['context']}", |
| 230 |
] |
| 231 |
else: |
| 232 |
assert "hashAlg" not in tc or tc["hashAlg"] == "none" |
| 233 |
externalMu = 0 |
| 234 |
if tg["externalMu"] is True: |
| 235 |
externalMu = 1 |
| 236 |
assert len(tc["mu"]) == 2 * 64 |
| 237 |
msg = tc["mu"] |
| 238 |
else: |
| 239 |
assert len(tc["message"]) <= 2 * 65536 |
| 240 |
msg = tc["message"] |
| 241 |
|
| 242 |
target = "sigGenInternalDeterministic" if is_deterministic else "sigGenInternal" |
| 243 |
acvp_call = exec_prefix + [ |
| 244 |
acvp_bin, |
| 245 |
target, |
| 246 |
f"message={msg}", |
| 247 |
f"sk={tc['sk']}", |
| 248 |
f"externalMu={externalMu}", |
| 249 |
] |
| 250 |
|
| 251 |
|
| 252 |
if not is_deterministic: |
| 253 |
acvp_call.append(f"rnd={tc['rnd']}") |
| 254 |
|
| 255 |
result = subprocess.run(acvp_call, encoding="utf-8", capture_output=True) |
| 256 |
if result.returncode != 0: |
| 257 |
err("FAIL!") |
| 258 |
err(f"{acvp_call} failed with error code {result.returncode}") |
| 259 |
err(result.stderr) |
| 260 |
exit(1) |
| 261 |
|
| 262 |
for l in result.stdout.splitlines(): |
| 263 |
(k, v) = l.split("=") |
| 264 |
results[k] = v |
| 265 |
info("done") |
| 266 |
return results |
| 267 |
|
| 268 |
|
| 269 |
def run_sigVer_test(tg, tc): |
| 270 |
info(f"Running sigVer test case {tc['tcId']} ... ", end="") |
| 271 |
results = {"tcId": tc["tcId"]} |
| 272 |
acvp_bin = get_acvp_binary(tg) |
| 273 |
|
| 274 |
if "preHash" in tg and tg["preHash"] == "preHash": |
| 275 |
assert len(tc["context"]) <= 2 * 255 |
| 276 |
|
| 277 |
|
| 278 |
if tc["hashAlg"] == "SHAKE-256": |
| 279 |
acvp_call = exec_prefix + [ |
| 280 |
acvp_bin, |
| 281 |
"sigVerPreHashShake256", |
| 282 |
f"message={tc['message']}", |
| 283 |
f"context={tc['context']}", |
| 284 |
f"signature={tc['signature']}", |
| 285 |
f"pk={tc['pk']}", |
| 286 |
] |
| 287 |
else: |
| 288 |
ph = compute_hash(tc["message"], tc["hashAlg"]) |
| 289 |
acvp_call = exec_prefix + [ |
| 290 |
acvp_bin, |
| 291 |
"sigVerPreHash", |
| 292 |
f"ph={ph}", |
| 293 |
f"context={tc['context']}", |
| 294 |
f"signature={tc['signature']}", |
| 295 |
f"pk={tc['pk']}", |
| 296 |
f"hashAlg={tc['hashAlg']}", |
| 297 |
] |
| 298 |
elif tg["signatureInterface"] == "external": |
| 299 |
assert "hashAlg" not in tc or tc["hashAlg"] == "none" |
| 300 |
assert len(tc["context"]) <= 2 * 255 |
| 301 |
assert len(tc["message"]) <= 2 * 65536 |
| 302 |
|
| 303 |
acvp_call = exec_prefix + [ |
| 304 |
acvp_bin, |
| 305 |
"sigVer", |
| 306 |
f"message={tc['message']}", |
| 307 |
f"context={tc['context']}", |
| 308 |
f"signature={tc['signature']}", |
| 309 |
f"pk={tc['pk']}", |
| 310 |
] |
| 311 |
else: |
| 312 |
assert "hashAlg" not in tc or tc["hashAlg"] == "none" |
| 313 |
externalMu = 0 |
| 314 |
if tg["externalMu"] is True: |
| 315 |
externalMu = 1 |
| 316 |
assert len(tc["mu"]) == 2 * 64 |
| 317 |
msg = tc["mu"] |
| 318 |
else: |
| 319 |
assert len(tc["message"]) <= 2 * 65536 |
| 320 |
msg = tc["message"] |
| 321 |
|
| 322 |
acvp_call = exec_prefix + [ |
| 323 |
acvp_bin, |
| 324 |
"sigVerInternal", |
| 325 |
f"message={msg}", |
| 326 |
f"signature={tc['signature']}", |
| 327 |
f"pk={tc['pk']}", |
| 328 |
f"externalMu={externalMu}", |
| 329 |
] |
| 330 |
|
| 331 |
result = subprocess.run(acvp_call, encoding="utf-8", capture_output=True) |
| 332 |
|
| 333 |
results["testPassed"] = result.returncode == 0 |
| 334 |
info("done") |
| 335 |
return results |
| 336 |
|
| 337 |
|
| 338 |
def runTestSingle(promptName, prompt, expectedResultName, expectedResult, output): |
| 339 |
info(f"Running ACVP tests for {promptName}") |
| 340 |
|
| 341 |
assert expectedResult is not None or output is not None |
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
isAcvts = False |
| 351 |
if type(prompt) is list: |
| 352 |
isAcvts = True |
| 353 |
assert len(prompt) == 2 |
| 354 |
acvVersion = prompt[0] |
| 355 |
assert len(acvVersion) == 1 |
| 356 |
prompt = prompt[1] |
| 357 |
|
| 358 |
assert prompt["algorithm"] == "ML-DSA" |
| 359 |
assert ( |
| 360 |
prompt["mode"] == "keyGen" |
| 361 |
or prompt["mode"] == "sigGen" |
| 362 |
or prompt["mode"] == "sigVer" |
| 363 |
) |
| 364 |
|
| 365 |
|
| 366 |
results = prompt.copy() |
| 367 |
|
| 368 |
results["testGroups"] = [] |
| 369 |
for tg in prompt["testGroups"]: |
| 370 |
tgResult = { |
| 371 |
"tgId": tg["tgId"], |
| 372 |
"tests": [], |
| 373 |
} |
| 374 |
results["testGroups"].append(tgResult) |
| 375 |
for tc in tg["tests"]: |
| 376 |
if prompt["mode"] == "keyGen": |
| 377 |
result = run_keyGen_test(tg, tc) |
| 378 |
elif prompt["mode"] == "sigGen": |
| 379 |
result = run_sigGen_test(tg, tc) |
| 380 |
elif prompt["mode"] == "sigVer": |
| 381 |
result = run_sigVer_test(tg, tc) |
| 382 |
tgResult["tests"].append(result) |
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
if isAcvts is True: |
| 388 |
results = [acvVersion, results] |
| 389 |
|
| 390 |
|
| 391 |
if expectedResult is not None: |
| 392 |
info(f"Comparing results with {expectedResultName}") |
| 393 |
|
| 394 |
|
| 395 |
if json.dumps(results) != json.dumps(expectedResult): |
| 396 |
err("FAIL!") |
| 397 |
err(f"Mismatching result for {promptName}") |
| 398 |
exit(1) |
| 399 |
info("OK") |
| 400 |
else: |
| 401 |
info( |
| 402 |
"Results could not be validated as no expected resulted were provided to --expected" |
| 403 |
) |
| 404 |
|
| 405 |
|
| 406 |
if output is not None: |
| 407 |
info(f"Writing results to {output}") |
| 408 |
with open(output, "w") as f: |
| 409 |
json.dump(results, f) |
| 410 |
|
| 411 |
|
| 412 |
def runTest(data, output): |
| 413 |
|
| 414 |
assert output is None or len(data) == 1 |
| 415 |
|
| 416 |
for promptName, prompt, expectedResultName, expectedResult in data: |
| 417 |
runTestSingle(promptName, prompt, expectedResultName, expectedResult, output) |
| 418 |
info("ALL GOOD!") |
| 419 |
|
| 420 |
|
| 421 |
def test(prompt, expected, output, version): |
| 422 |
assert ( |
| 423 |
prompt is not None or output is None |
| 424 |
), "cannot produce output if there is no input" |
| 425 |
|
| 426 |
assert prompt is None or ( |
| 427 |
output is not None or expected is not None |
| 428 |
), "if there is a prompt, either output or expectedResult required" |
| 429 |
|
| 430 |
|
| 431 |
if prompt is not None: |
| 432 |
data = [loadAcvpData(prompt, expected)] |
| 433 |
else: |
| 434 |
|
| 435 |
data = loadDefaultAcvpData(version) |
| 436 |
|
| 437 |
runTest(data, output) |
| 438 |
|
| 439 |
|
| 440 |
parser = argparse.ArgumentParser() |
| 441 |
parser.add_argument( |
| 442 |
"-p", "--prompt", help="Path to prompt file in json format", required=False |
| 443 |
) |
| 444 |
parser.add_argument( |
| 445 |
"-e", |
| 446 |
"--expected", |
| 447 |
help="Path to expectedResults file in json format", |
| 448 |
required=False, |
| 449 |
) |
| 450 |
parser.add_argument( |
| 451 |
"-o", "--output", help="Path to output file in json format", required=False |
| 452 |
) |
| 453 |
parser.add_argument( |
| 454 |
"--version", |
| 455 |
"-v", |
| 456 |
default="v1.1.0.41", |
| 457 |
help="ACVP test vector version (default: v1.1.0.41)", |
| 458 |
) |
| 459 |
args = parser.parse_args() |
| 460 |
|
| 461 |
if args.prompt is None: |
| 462 |
print(f"Using ACVP test vectors version {args.version}", file=sys.stderr) |
| 463 |
|
| 464 |
|
| 465 |
if not download_acvp_files(args.version): |
| 466 |
print("Failed to download ACVP test files", file=sys.stderr) |
| 467 |
sys.exit(1) |
| 468 |
|
| 469 |
test(args.prompt, args.expected, args.output, args.version) |