omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / om / tls / test / mlkem / gen_vectors.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | # Test tooling only (no primitive is implemented here): converts the upstream vector sources into the |
| 4 | # flat record files driver.om reads. Usage, from the omega-mv root: |
| 5 | # python3 om/tls/test/mlkem/gen_vectors.py WYCHEPROOF_DIR NIST_DIR ACVP_DIR |
| 6 | # Inputs: |
| 7 | # WYCHEPROOF_DIR/testvectors_v1/mlkem_768_{keygen_seed,encaps,semi_expanded_decaps,}_test.json |
| 8 | # (C2SP/wycheproof d17cc89f) |
| 9 | # NIST_DIR/SHA3_{256,512}{ShortMsg,LongMsg}.rsp, SHAKE{128,256}{ShortMsg,LongMsg,VariableOut}.rsp |
| 10 | # (CAVP sha-3bytetestvectors.zip, shakebytetestvectors.zip) |
| 11 | # ACVP_DIR/gen-val/json-files/ML-KEM-{keyGen,encapDecap}-FIPS203/internalProjection.json |
| 12 | # (usnistgov/ACVP-Server 975de31e) |
| 13 | # Every numberOfTests / per-group count is asserted, so a silently shrunk source fails here. |
| 14 | # The expected return codes are derived from the published result plus the length rules of the |
| 15 | # library API (2 = bad length, 1 = ek modulus check, 3 = dk hash check) and asserted per reason. |
| 16 | import hashlib |
| 17 | import json |
| 18 | import os |
| 19 | import re |
| 20 | import sys |
| 21 | |
| 22 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 23 | VEC = os.path.join(HERE, "vectors") |
| 24 | EK, DK, CT = 1184, 2400, 1088 |
| 25 | |
| 26 | |
| 27 | def sha256_file(p): |
| 28 | return hashlib.sha256(open(p, "rb").read()).hexdigest() |
| 29 | |
| 30 | |
| 31 | def hx(s): |
| 32 | return s if s else "-" |
| 33 | |
| 34 | |
| 35 | def blen(h): |
| 36 | assert len(h) % 2 == 0, h[:20] |
| 37 | return len(h) // 2 |
| 38 | |
| 39 | |
| 40 | def write(name, header, recs): |
| 41 | recs = [r.lower() for r in recs] # ACVP hex is uppercase; record letters are restored below |
| 42 | recs = [r[0].upper() + r[1:] for r in recs] |
| 43 | with open(os.path.join(VEC, name), "w") as f: |
| 44 | for h in header: |
| 45 | f.write("# " + h + "\n") |
| 46 | for r in recs: |
| 47 | f.write(r + "\n") |
| 48 | print(f"{name}: {len(recs)} records") |
| 49 | |
| 50 | |
| 51 | def wycheproof(wdir): |
| 52 | base = os.path.join(wdir, "testvectors_v1") |
| 53 | recs, hdr = [], [ |
| 54 | "Wycheproof ML-KEM-768 vectors (C2SP/wycheproof d17cc89f, Apache-2.0: WYCHEPROOF.LICENSE).", |
| 55 | "Generated by gen_vectors.py. Record formats: see driver.om."] |
| 56 | counts = {} |
| 57 | |
| 58 | def load(n): |
| 59 | p = os.path.join(base, n) |
| 60 | j = json.load(open(p)) |
| 61 | tests = [t for g in j["testGroups"] for t in g["tests"]] |
| 62 | assert len(tests) == j["numberOfTests"], n |
| 63 | hdr.append(f"{n} sha256 {sha256_file(p)} numberOfTests {len(tests)}") |
| 64 | counts[n] = len(tests) |
| 65 | return tests |
| 66 | |
| 67 | for t in load("mlkem_768_keygen_seed_test.json"): |
| 68 | assert t["result"] == "valid" and blen(t["seed"]) == 64 |
| 69 | recs.append(f"Q 0 {t['seed']} {t['ek']} {t['dk']}") |
| 70 | for t in load("mlkem_768_encaps_test.json"): |
| 71 | assert blen(t["m"]) == 32 |
| 72 | if t["result"] == "valid": |
| 73 | recs.append(f"E 0 {t['ek']} {t['m']} {t['c']} {t['K']}") |
| 74 | else: |
| 75 | rc = 2 if blen(t["ek"]) != EK else 1 |
| 76 | recs.append(f"E {rc} {t['ek']} {t['m']} - -") |
| 77 | for t in load("mlkem_768_semi_expanded_decaps_test.json"): |
| 78 | if t["result"] == "valid": |
| 79 | rc = 0 |
| 80 | elif blen(t["dk"]) != DK or blen(t["c"]) != CT: |
| 81 | rc = 2 |
| 82 | else: |
| 83 | rc = 3 |
| 84 | recs.append(f"D {rc} {t['dk']} {t['c']} {hx(t['K']) if rc == 0 else '-'}") |
| 85 | for t in load("mlkem_768_test.json"): |
| 86 | if blen(t["seed"]) != 64: |
| 87 | assert t["result"] == "invalid" |
| 88 | recs.append(f"C 2 {t['seed']} - - 0 -") |
| 89 | continue |
| 90 | if t["result"] == "valid": |
| 91 | r2 = 0 |
| 92 | else: |
| 93 | assert blen(t["c"]) != CT, t["tcId"] |
| 94 | r2 = 2 |
| 95 | recs.append(f"C 0 {t['seed']} {hx(t['ek'])} {t['c']} {r2} {hx(t['K']) if r2 == 0 else '-'}") |
| 96 | write("wycheproof.txt", hdr, recs) |
| 97 | return counts |
| 98 | |
| 99 | |
| 100 | def acvp(adir): |
| 101 | root = os.path.join(adir, "gen-val/json-files") |
| 102 | recs = [] |
| 103 | hdr = ["NIST ACVP-Server (usnistgov/ACVP-Server 975de31e) ML-KEM FIPS 203 internalProjection", |
| 104 | "vectors, parameter set ML-KEM-768 only (notice: NIST.NOTICE). Generated by gen_vectors.py."] |
| 105 | p = os.path.join(root, "ML-KEM-keyGen-FIPS203/internalProjection.json") |
| 106 | hdr.append(f"ML-KEM-keyGen-FIPS203/internalProjection.json sha256 {sha256_file(p)}") |
| 107 | groups = [g for g in json.load(open(p))["testGroups"] if g["parameterSet"] == "ML-KEM-768"] |
| 108 | assert len(groups) == 1 and len(groups[0]["tests"]) == 25 |
| 109 | for t in groups[0]["tests"]: |
| 110 | recs.append(f"K {t['d']} {t['z']} {t['ek']} {t['dk']}") |
| 111 | p = os.path.join(root, "ML-KEM-encapDecap-FIPS203/internalProjection.json") |
| 112 | hdr.append(f"ML-KEM-encapDecap-FIPS203/internalProjection.json sha256 {sha256_file(p)}") |
| 113 | groups = [g for g in json.load(open(p))["testGroups"] if g["parameterSet"] == "ML-KEM-768"] |
| 114 | want = {"encapsulation": 25, "decapsulation": 10, "decapsulationKeyCheck": 10, |
| 115 | "encapsulationKeyCheck": 10} |
| 116 | assert sorted(g["function"] for g in groups) == sorted(want) |
| 117 | zc = "00" * CT |
| 118 | for g in groups: |
| 119 | assert len(g["tests"]) == want[g["function"]], g["function"] |
| 120 | for t in g["tests"]: |
| 121 | f = g["function"] |
| 122 | if f == "encapsulation": |
| 123 | recs.append(f"E 0 {t['ek']} {t['m']} {t['c']} {t['k']}") |
| 124 | recs.append(f"D 0 {t['dk']} {t['c']} {t['k']}") |
| 125 | elif f == "decapsulation": |
| 126 | assert t["reason"] in ("valid decapsulation", "modified ciphertext") |
| 127 | recs.append(f"D 0 {t['dk']} {t['c']} {t['k']}") |
| 128 | elif f == "decapsulationKeyCheck": |
| 129 | assert t["testPassed"] == (t["reason"] == "valid decapsulation key") |
| 130 | assert t["testPassed"] or t["reason"] == "modified H" |
| 131 | recs.append(f"D {0 if t['testPassed'] else 3} {t['dk']} {zc} -") |
| 132 | else: |
| 133 | assert t["testPassed"] or t["reason"] == "noisy linear system values too large" |
| 134 | recs.append(f"E {0 if t['testPassed'] else 1} {t['ek']} {'00' * 32} - -") |
| 135 | write("acvp.txt", hdr, recs) |
| 136 | return len(recs) |
| 137 | |
| 138 | |
| 139 | def rsp(path, alg, outkey): |
| 140 | """(msg hex, out hex) pairs of a CAVP byte-oriented .rsp; Len in bits, Msg 00 when Len = 0.""" |
| 141 | text = open(path).read() |
| 142 | out, ln, msg = [], None, None |
| 143 | for line in text.splitlines(): |
| 144 | m = re.match(r"^(Len|Msg|Outputlen|" + outkey + r") = (\S*)$", line.strip()) |
| 145 | if not m: |
| 146 | continue |
| 147 | k, v = m.groups() |
| 148 | if k == "Len": |
| 149 | ln = int(v) |
| 150 | elif k == "Msg": |
| 151 | msg = v |
| 152 | elif k == outkey: |
| 153 | if ln is not None: |
| 154 | assert ln % 8 == 0 |
| 155 | msg = msg[:ln // 4] |
| 156 | out.append(f"{alg} {hx(msg)} {v}") |
| 157 | ln, msg = None, None |
| 158 | return out |
| 159 | |
| 160 | |
| 161 | def nist(ndir): |
| 162 | hdr = ["NIST CAVP SHA-3 / SHAKE byte-oriented vectors (sha-3bytetestvectors.zip,", |
| 163 | "shakebytetestvectors.zip; notice: NIST.NOTICE). Generated by gen_vectors.py.", |
| 164 | "H A MSG OUT: one-shot; S A MSG OUT: every 10th LongMsg vector again, chunked absorb/squeeze.", |
| 165 | "A: 1 SHA3-256, 2 SHA3-512, 3 SHAKE128, 4 SHAKE256."] |
| 166 | recs = [] |
| 167 | plan = [("SHA3_256ShortMsg.rsp", 1, "MD"), ("SHA3_256LongMsg.rsp", 1, "MD"), |
| 168 | ("SHA3_512ShortMsg.rsp", 2, "MD"), ("SHA3_512LongMsg.rsp", 2, "MD"), |
| 169 | ("SHAKE128ShortMsg.rsp", 3, "Output"), ("SHAKE128LongMsg.rsp", 3, "Output"), |
| 170 | ("SHAKE128VariableOut.rsp", 3, "Output"), |
| 171 | ("SHAKE256ShortMsg.rsp", 4, "Output"), ("SHAKE256LongMsg.rsp", 4, "Output"), |
| 172 | ("SHAKE256VariableOut.rsp", 4, "Output")] |
| 173 | # count per file = its Len = lines (COUNT = lines for VariableOut), counted independently of the parser |
| 174 | for name, alg, key in plan: |
| 175 | p = os.path.join(ndir, name) |
| 176 | r = rsp(p, alg, key) |
| 177 | hdr.append(f"{name} sha256 {sha256_file(p)} cases {len(r)}") |
| 178 | n = len(re.findall(r"^COUNT = " if "VariableOut" in name else r"^Len = ", open(p).read(), re.M)) |
| 179 | assert len(r) == n and n > 0, (name, len(r), n) |
| 180 | recs += ["H " + x for x in r] |
| 181 | if "LongMsg" in name: |
| 182 | recs += ["S " + x for x in r[::10]] # every 10th long message, streamed |
| 183 | write("nist-sha3.txt", hdr, recs) |
| 184 | return len(recs) |
| 185 | |
| 186 | |
| 187 | if __name__ == "__main__": |
| 188 | w, n, a = sys.argv[1:4] |
| 189 | print(wycheproof(w)) |
| 190 | print(acvp(a)) |
| 191 | print(nist(n)) |