interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / om / tls / test / ec / gen_vectors.py

227 lines · 10311 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3# Test tooling only (no primitive is implemented here): converts the Wycheproof ECDSA JSON files and
4# the NIST CAVP 186-4 SigVer.rsp into the flat vector files read by om/tls/test/ec/driver.om.
5# hashlib computes the reference digest column, which the driver cross-checks against its own
6# sha2_digest (om/tls/sha2.om) before every verify.
7#
8# Usage: python3 gen_vectors.py WYCHEPROOF_DIR CAVP_ZIP OUT_DIR
9#
10# Line format (space separated, '#' starts a comment line, '-' is an empty hex field):
11# ID CRV MODE EXP ALG PUBHEX SIGHEX MSGHEX DIGESTHEX
12# CRV 256|384; MODE d (DER) or r (raw r||s, IEEE P1363); EXP 0 valid / 1 must be refused;
13# ALG 256|384|512 (SHA-2 digest of MSG).
14import hashlib
15import json
16import os
17import subprocess
18import sys
19import zipfile
20
21WY_FILES = [
22 "ecdsa_secp256r1_sha256_test.json",
23 "ecdsa_secp256r1_sha256_p1363_test.json",
24 "ecdsa_secp256r1_sha512_test.json",
25 "ecdsa_secp256r1_sha512_p1363_test.json",
26 "ecdsa_secp384r1_sha256_test.json",
27 "ecdsa_secp384r1_sha384_test.json",
28 "ecdsa_secp384r1_sha384_p1363_test.json",
29 "ecdsa_secp384r1_sha512_test.json",
30 "ecdsa_secp384r1_sha512_p1363_test.json",
31]
32CURVES = {"secp256r1": 256, "secp384r1": 384, "P-256": 256, "P-384": 384}
33SHAS = {"SHA-256": 256, "SHA-384": 384, "SHA-512": 512}
34CAVP_URL = ("https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/"
35 "documents/dss/186-4ecdsatestvectors.zip")
36
37
38def digest(alg, msg):
39 return {256: hashlib.sha256, 384: hashlib.sha384, 512: hashlib.sha512}[alg](msg).hexdigest()
40
41
42def hx(s):
43 return s if s else "-"
44
45
46def der(r, s):
47 # minimal DER Ecdsa-Sig-Value (both parts positive), so every CAVP case also runs through the
48 # DER entry point
49 def integer(v):
50 b = v.to_bytes(max(1, (v.bit_length() + 8) // 8), "big")
51 return b"\x02" + bytes([len(b)]) + b
52 body = integer(r) + integer(s)
53 return (b"\x30" + bytes([len(body)]) + body).hex()
54
55
56def sha256_file(path):
57 with open(path, "rb") as f:
58 return hashlib.sha256(f.read()).hexdigest()
59
60
61def wycheproof(wdir, name, out):
62 path = os.path.join(wdir, "testvectors_v1", name)
63 d = json.load(open(path))
64 commit = subprocess.run(["git", "-C", wdir, "rev-parse", "HEAD"], capture_output=True,
65 text=True, check=True).stdout.strip()
66 tag = name[len("ecdsa_"):-len("_test.json")]
67 lines = [
68 "# source: https://github.com/C2SP/wycheproof testvectors_v1/" + name,
69 "# commit: " + commit + " sha256: " + sha256_file(path),
70 "# license: Apache-2.0 (see LICENSE.wycheproof beside this file)",
71 "# numberOfTests: %d" % d["numberOfTests"],
72 ]
73 count = {"valid": 0, "invalid": 0}
74 for g in d["testGroups"]:
75 crv = CURVES[g["publicKey"]["curve"]]
76 alg = SHAS[g["sha"]]
77 mode = {"EcdsaVerify": "d", "EcdsaP1363Verify": "r"}[g["type"]]
78 pub = g["publicKey"]["uncompressed"]
79 for t in g["tests"]:
80 res = t["result"]
81 if res not in count:
82 raise SystemExit("%s tcId %d: result %s not handled" % (name, t["tcId"], res))
83 count[res] += 1
84 exp = 0 if res == "valid" else 1
85 msg = bytes.fromhex(t["msg"])
86 lines.append("w-%s-%d %d %s %d %d %s %s %s %s" % (
87 tag, t["tcId"], crv, mode, exp, alg, pub, hx(t["sig"]), hx(t["msg"]),
88 digest(alg, msg)))
89 if count["valid"] + count["invalid"] != d["numberOfTests"]:
90 raise SystemExit(name + ": test count disagrees with numberOfTests")
91 lines.insert(4, "# valid %d invalid %d acceptable 0" % (count["valid"], count["invalid"]))
92 with open(os.path.join(out, "wycheproof_" + tag + ".txt"), "w") as f:
93 f.write("\n".join(lines) + "\n")
94
95
96def cavp(zpath, out):
97 with zipfile.ZipFile(zpath) as z:
98 text = z.read("186-4ecdsatestvectors/SigVer.rsp").decode()
99 lines = [
100 "# source: " + CAVP_URL + " member 186-4ecdsatestvectors/SigVer.rsp",
101 "# zip sha256: " + sha256_file(zpath),
102 "# license: NIST CAVP test data, a work of the U.S. Government (see NOTICE.cavp)",
103 "# sections P-256 and P-384 with SHA-256, SHA-384, SHA-512 (other sections NOT_RUN)",
104 ]
105 sec = None
106 cur = {}
107 n = {"P": 0, "F": 0}
108 idx = 0
109 for raw in text.splitlines():
110 s = raw.strip()
111 if s.startswith("["):
112 c, h = s[1:-1].split(",")
113 sec = (CURVES[c], SHAS[h]) if c in CURVES and h in SHAS else None
114 idx = 0
115 continue
116 if sec is None or "=" not in s:
117 continue
118 k, v = [x.strip() for x in s.split("=", 1)]
119 cur[k] = v
120 if k != "Result":
121 continue
122 crv, alg = sec
123 idx += 1
124 w = crv // 4
125 pub = "04" + cur["Qx"].rjust(w, "0") + cur["Qy"].rjust(w, "0")
126 sig = cur["R"].rjust(w, "0") + cur["S"].rjust(w, "0")
127 r = v[0]
128 n[r] += 2
129 msg = bytes.fromhex(cur["Msg"])
130 for mode, sg in (("r", sig), ("d", der(int(cur["R"], 16), int(cur["S"], 16)))):
131 lines.append("c-p%d-sha%d-%d%s %d %s %d %d %s %s %s %s" % (
132 crv, alg, idx, mode, crv, mode, 0 if r == "P" else 1, alg, pub, sg, cur["Msg"],
133 digest(alg, msg)))
134 cur = {}
135 lines.insert(4, "# lines: P (valid) %d F (invalid) %d (each case twice: raw r||s and DER)" % (n["P"], n["F"]))
136 with open(os.path.join(out, "cavp_sigver.txt"), "w") as f:
137 f.write("\n".join(lines) + "\n")
138
139
140P = {256: int("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", 16),
141 384: int("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"
142 "ffffffff0000000000000000ffffffff", 16)}
143N = {256: int("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 16),
144 384: int("ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf"
145 "581a0db248b0a77aecec196accc52973", 16)}
146
147
148def edge(wdir, out):
149 # Hand-made encoding cases with an exact expected code (EXP "=K"), each derived from a valid
150 # DER test of a Wycheproof file. Constants p, n: FIPS 186-4 D.1.2.3 / D.1.2.4.
151 lines = ["# edge cases derived from Wycheproof (Apache-2.0, see LICENSE.wycheproof); EXP =K means",
152 "# the exact return code K is required (0 valid, 2 encoding, 3 key, 4 range, 5 curve)"]
153 for crv, name in ((256, "ecdsa_secp256r1_sha256_test.json"), (384, "ecdsa_secp384r1_sha384_test.json")):
154 d = json.load(open(os.path.join(wdir, "testvectors_v1", name)))
155 g = d["testGroups"][0]
156 # first valid test whose r INTEGER is exactly crv/8 bytes with top byte < 0x80, so that a
157 # single 0x00 pad (der-int-pad) is a non-minimal encoding of a value that would verify
158 t = next(t for t in g["tests"] if t["result"] == "valid" and
159 int(t["sig"][6:8], 16) == crv // 8 and int(t["sig"][8:10], 16) < 0x80)
160 alg = SHAS[g["sha"]]
161 pub = g["publicKey"]["uncompressed"]
162 sig = t["sig"]
163 msg = bytes.fromhex(t["msg"])
164 dg = digest(alg, msg)
165 w = crv // 4
166 x, y = int(pub[2:2 + w], 16), int(pub[2 + w:], 16)
167 b = bytes.fromhex(sig)
168 rl = b[3]
169 r = int.from_bytes(b[4:4 + rl], "big")
170 s = int.from_bytes(b[6 + rl:], "big")
171 raw = r.to_bytes(crv // 8, "big").hex() + s.to_bytes(crv // 8, "big").hex()
172 h = lambda v: v.to_bytes(crv // 8, "big").hex()
173 cases = [
174 ("valid", crv, "d", "=0", pub, sig),
175 ("valid-raw", crv, "r", "=0", pub, raw),
176 ("crv521", 521, "d", "=5", pub, sig),
177 ("crv0", 0, "r", "=5", pub, raw),
178 ("other-crv", 384 if crv == 256 else 256, "d", "=3", pub, sig),
179 ("pub-compressed", crv, "d", "=3", "02" + pub[2:2 + w], sig),
180 ("pub-prefix", crv, "d", "=3", "06" + pub[2:], sig),
181 ("pub-short", crv, "d", "=3", pub[:-2], sig),
182 ("pub-long", crv, "d", "=3", pub + "00", sig),
183 ("pub-x-eq-p", crv, "d", "=3", "04" + h(P[crv]) + h(y), sig),
184 ("pub-y-eq-p", crv, "d", "=3", "04" + h(x) + h(P[crv]), sig),
185 ("pub-y+p-wraps", crv, "d", "=3", "04" + h(x) + h((y + P[crv]) % (1 << crv)), sig),
186 ("pub-off-curve", crv, "d", "=3", "04" + h(x) + h(y ^ 1), sig),
187 ("pub-zero", crv, "d", "=3", "04" + h(0) + h(0), sig),
188 ("der-trailing", crv, "d", "=2", pub, sig + "00"),
189 ("der-empty", crv, "d", "=2", pub, ""),
190 ("der-long-len", crv, "d", "=2", pub, "3081" + sig[2:]),
191 ("der-int-pad", crv, "d", "=2", pub, der_raw(b"\x00" + r.to_bytes(crv // 8, "big"), s)),
192 ("der-neg-r", crv, "d", "=2", pub, der_raw(b"\x80" + bytes(crv // 8 - 1), s)),
193 ("der-tag", crv, "d", "=2", pub, "31" + sig[2:]),
194 ("raw-short", crv, "r", "=2", pub, raw[:-2]),
195 ("raw-long", crv, "r", "=2", pub, raw + "00"),
196 ("r-zero", crv, "r", "=4", pub, h(0) + h(s)),
197 ("s-zero", crv, "d", "=4", pub, der(r, 0)),
198 ("r-eq-n", crv, "d", "=4", pub, der(N[crv], s)),
199 ("s-eq-n", crv, "r", "=4", pub, h(r) + h(N[crv])),
200 ("r-too-long", crv, "d", "=4", pub, der_raw(b"\x01" + bytes(crv // 8), s)),
201 ("s-max", crv, "r", "=4", pub, h(r) + "ff" * (crv // 8)),
202 ]
203 for cid, c, mode, exp, pk, sg in cases:
204 lines.append("e-p%d-%s %d %s %s %d %s %s %s %s" % (crv, cid, c, mode, exp, alg, hx(pk), hx(sg),
205 hx(t["msg"]), dg))
206 with open(os.path.join(out, "edge.txt"), "w") as f:
207 f.write("\n".join(lines) + "\n")
208
209
210def der_raw(rb, s):
211 # DER-shaped signature whose r INTEGER content is rb verbatim (for non-minimal / negative r)
212 sb = s.to_bytes(max(1, (s.bit_length() + 8) // 8), "big")
213 body = b"\x02" + bytes([len(rb)]) + rb + b"\x02" + bytes([len(sb)]) + sb
214 return (b"\x30" + bytes([len(body)]) + body).hex()
215
216
217def main():
218 wdir, zpath, out = sys.argv[1:4]
219 os.makedirs(out, exist_ok=True)
220 for name in WY_FILES:
221 wycheproof(wdir, name, out)
222 cavp(zpath, out)
223 edge(wdir, out)
224
225
226if __name__ == "__main__":
227 main()