Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/om/tls/test/ecdh/gen_vectors.py # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / om / tls / test / ecdh / gen_vectors.py` 270 lines ยท 12200 bytes Raw Blame History 1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: Apache-2.0 3 # Test tooling only (an oracle and a format converter, not part of the library): converts the NIST 4 # CAVP ECC CDH primitive vectors and the Wycheproof ECDH files into the flat vector files read by 5 # om/tls/test/ecdh/driver.om, and writes the edge-case file. A plain-integer reference (affine 6 # double-and-add, variable time, test-only) recomputes every expected value; a source vector that 7 # disagrees with it stops the conversion. 8 # 9 # Usage: python3 gen_vectors.py WYCHEPROOF_DIR CAVP_ZIP OUT_DIR 10 # 11 # Line format (space separated, '#' starts a comment line, '-' is an empty hex field): 12 # ID OP RC DHEX PHEX XHEX 13 # OP S ecdh_shared (X = shared secret, zeros when RC != 0), P ecdh_pub (P '-', X = 04||x||y), 14 # C ecdh_pct (P = public key to check, X '-'). RC is the exact return code. 15 import hashlib 16 import json 17 import os 18 import sys 19 import zipfile 20 21 CURVES = { 22 256: dict( 23 name="secp256r1", cavp="P-256", 24 p=0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF, 25 n=0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551, 26 b=0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B, 27 gx=0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 28 gy=0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5, 29 spki="`3059301306072a8648ce3d020106082a8648ce3d030107034200`"), 30 384: dict( 31 name="secp384r1", cavp="P-384", 32 p=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF, 33 n=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973, 34 b=0xB3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF, 35 gx=0xAA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7, 36 gy=0x3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F, 37 spki="`3076301006072a8648ce3d020106052b81040022036200`"), 38 } 39 NB = {256: 32, 384: 48} 40 41 42 def on_curve(c, x, y): 43 k = CURVES[c] 44 return x < k["p"] and y < k["p"] and (y * y - x ** 3 + 3 * x - k["b"]) % k["p"] == 0 45 46 47 def padd(c, a, b): 48 p = CURVES[c]["p"] 49 if a is None: 50 return b 51 if b is None: 52 return a 53 if a[0] == b[0]: 54 if (a[1] + b[1]) % p == 0: 55 return None 56 lam = (3 * a[0] * a[0] - 3) * pow(2 * a[1], p - 2, p) % p 57 else: 58 lam = (b[1] - a[1]) * pow(b[0] - a[0], p - 2, p) % p 59 x = (lam * lam - a[0] - b[0]) % p 60 return (x, (lam * (a[0] - x) - a[1]) % p) 61 62 63 def smul(c, k, pt): 64 r = None 65 for bit in bin(k)[2:] if k else "": 66 r = padd(c, r, r) 67 if bit == "1": 68 r = padd(c, r, pt) 69 return r 70 71 72 def enc(c, pt): 73 nb = NB[c] 74 return "04" + pt[0].to_bytes(nb, "big").hex() + pt[1].to_bytes(nb, "big").hex() 75 76 77 def dec(c, h): 78 nb = NB[c] 79 b = bytes.fromhex(h) 80 if len(b) != 1 + 2 * nb or b[0] != 4: 81 return None 82 x, y = int.from_bytes(b[1:1 + nb], "big"), int.from_bytes(b[1 + nb:], "big") 83 return (x, y) if on_curve(c, x, y) else None 84 85 86 def shared_ref(c, d, ph): 87 """(rc, z hex) the library must give for ecdh_shared(d, P)""" 88 nb = NB[c] 89 pt = dec(c, ph) 90 if pt is None: 91 return 3, "00" * nb 92 if not 1 <= d < CURVES[c]["n"]: 93 return 4, "00" * nb 94 r = smul(c, d, pt) 95 if r is None: 96 return 1, "00" * nb 97 return 0, r[0].to_bytes(nb, "big").hex() 98 99 100 def pub_ref(c, d): 101 nb = NB[c] 102 if not 1 <= d < CURVES[c]["n"]: 103 return 4, "00" * (1 + 2 * nb) 104 k = CURVES[c] 105 return 0, enc(c, smul(c, d, (k["gx"], k["gy"]))) 106 107 108 def dhex(c, d): 109 return d.to_bytes(NB[c], "big").hex() 110 111 112 def cavp(zpath, out): 113 raw = zipfile.ZipFile(zpath).read("KAS_ECC_CDH_PrimitiveTest.txt").decode() 114 lines, cur, rec, n = [], None, {}, 0 115 for ln in raw.splitlines(): 116 ln = ln.strip() 117 if ln.startswith("["): 118 cur = {"[P-256]": 256, "[P-384]": 384}.get(ln) 119 continue 120 if cur is None or "=" not in ln: 121 continue 122 k, v = [s.strip() for s in ln.split("=", 1)] 123 rec[k] = v 124 if k == "ZIUT": 125 c, nb = cur, NB[cur] 126 d = int(rec["dIUT"], 16) 127 peer = "04" + rec["QCAVSx"].zfill(2 * nb) + rec["QCAVSy"].zfill(2 * nb) 128 q = "04" + rec["QIUTx"].zfill(2 * nb) + rec["QIUTy"].zfill(2 * nb) 129 z = rec["ZIUT"].zfill(2 * nb) 130 if shared_ref(c, d, peer) != (0, z) or pub_ref(c, d) != (0, q): 131 sys.exit("cavp %s COUNT %s disagrees with the reference" % (c, rec["COUNT"])) 132 lines.append("cavp-%d-%s S 0 %s %s %s" % (c, rec["COUNT"], dhex(c, d), peer, z)) 133 lines.append("cavp-%d-%s-pub P 0 %s - %s" % (c, rec["COUNT"], dhex(c, d), q)) 134 n += 1 135 rec = {} 136 with open(os.path.join(out, "cavp_cdh.txt"), "w") as f: 137 f.write("# NIST CAVP KAS_ECC_CDH_PrimitiveTest.txt [P-256] and [P-384] (see NOTICE.cavp)\n") 138 f.write("\n".join(lines) + "\n") 139 return n 140 141 142 def wy_ecpoint(wdir, c, out): 143 path = os.path.join(wdir, "ecdh_%s_ecpoint_test.json" % CURVES[c]["name"]) 144 doc = json.load(open(path)) 145 lines = [] 146 for g in doc["testGroups"]: 147 for t in g["tests"]: 148 d = int(t["private"], 16) 149 rc, z = shared_ref(c, d, t["public"]) 150 if t["result"] == "valid": 151 if rc != 0 or z != t["shared"]: 152 sys.exit("%s tcId %d valid but the reference gives %d" % (path, t["tcId"], rc)) 153 elif rc == 0: 154 if "CompressedPoint" not in t["flags"] and "CompressedPublic" not in t["flags"]: 155 sys.exit("%s tcId %d %s but the reference accepts it" % (path, t["tcId"], t["result"])) 156 lines.append("wy-%s-ecpoint-%d S %d %s %s %s" % (CURVES[c]["name"], t["tcId"], rc, dhex(c, d), 157 t["public"] or "-", z)) 158 name = "wycheproof_%s_ecpoint.txt" % CURVES[c]["name"] 159 with open(os.path.join(out, name), "w") as f: 160 f.write("# Wycheproof %s (sha256 %s)\n" % (os.path.basename(path), sha(path))) 161 f.write("# valid: the shared secret; invalid and compressed (acceptable): refused with 3, since a\n") 162 f.write("# TLS 1.3 key_share for secp256r1/secp384r1 is the uncompressed form only (RFC 8446 4.2.8.2)\n") 163 f.write("\n".join(lines) + "\n") 164 return len(lines) 165 166 167 def wy_asn(wdir, c, out, skipped): 168 """the SPKI-encoded file: cases whose key is the standard named-curve SPKI for this curve give the 169 raw point; every other case is counted per flag in skipped (the SPKI/ASN.1 layer is not in this 170 unit: a TLS key_share carries the raw point)""" 171 path = os.path.join(wdir, "ecdh_%s_test.json" % CURVES[c]["name"]) 172 pre = CURVES[c]["spki"] 173 lines = [] 174 for g in json.load(open(path))["testGroups"]: 175 for t in g["tests"]: 176 pk = t["public"] 177 if not pk.startswith(pre) or len(pk) != len(pre) + 2 * (1 + 2 * NB[c]): 178 key = "%s %s" % (os.path.basename(path), ",".join(sorted(t["flags"])) or "none") 179 skipped[key] = skipped.get(key, 0) + 1 180 continue 181 d = int(t["private"], 16) 182 pt = pk[len(pre):] 183 rc, z = shared_ref(c, d, pt) 184 if t["result"] == "valid" and (rc != 0 or z != t["shared"]): 185 sys.exit("%s tcId %d valid but the reference gives %d" % (path, t["tcId"], rc)) 186 if t["result"] == "invalid" and rc == 0: 187 sys.exit("%s tcId %d invalid but the reference accepts it" % (path, t["tcId"])) 188 lines.append("wy-%s-asn-%d S %d %s %s %s" % (CURVES[c]["name"], t["tcId"], rc, dhex(c, d), pt, z)) 189 name = "wycheproof_%s_spki.txt" % CURVES[c]["name"] 190 with open(os.path.join(out, name), "w") as f: 191 f.write("# Wycheproof %s (sha256 %s): named-curve SPKI cases, raw point extracted\n" 192 % (os.path.basename(path), sha(path))) 193 f.write("\n".join(lines) + "\n") 194 return len(lines) 195 196 197 def edge(out): 198 lines = [] 199 for c in (256, 384): 200 k, nb = CURVES[c], NB[c] 201 n, p = k["n"], k["p"] 202 g = (k["gx"], k["gy"]) 203 G = enc(c, g) 204 s = "edge-%d-" % c 205 for tag, d in (("d0", 0), ("d1", 1), ("d2", 2), ("dn-1", n - 1), ("dn", n), ("dn+1", n + 1), 206 ("dmax", 2 ** (8 * nb) - 1), ("dhigh", 2 ** (8 * nb - 1))): 207 rc, q = pub_ref(c, d) 208 lines.append("%spub-%s P %d %s - %s" % (s, tag, rc, dhex(c, d), q)) 209 rc, z = shared_ref(c, d, G) 210 lines.append("%sshared-%s S %d %s %s %s" % (s, tag, rc, dhex(c, d), G, z)) 211 d = 0x1234567 * 7919 + 3 212 Q = pub_ref(c, d)[1] 213 bad = [("infinity00", "00"), ("compressed", "02" + G[2:2 + 2 * nb]), 214 ("hybrid", "06" + G[2:]), ("prefix05", "05" + G[2:]), 215 ("x-eq-p", "04" + p.to_bytes(nb, "big").hex() + G[2 + 2 * nb:]), 216 ("y-eq-p", "04" + G[2:2 + 2 * nb] + p.to_bytes(nb, "big").hex()), 217 ("off-curve", G[:-2] + "%02x" % (int(G[-2:], 16) ^ 1)), 218 ("zero-point", "04" + "00" * (2 * nb)), ("short", G[:-2]), ("long", G + "00"), 219 ("empty", "-")] 220 for tag, pt in bad: 221 lines.append("%speer-%s S 3 %s %s %s" % (s, tag, dhex(c, d), pt, "00" * nb)) 222 # -G is valid: the ladder handles the inverse of the base point 223 ng = enc(c, (g[0], p - g[1])) 224 rc, z = shared_ref(c, d, ng) 225 lines.append("%speer-minusG S %d %s %s %s" % (s, rc, dhex(c, d), ng, z)) 226 # length codes: z one byte long (2), scalar one byte short (5) and long (5) 227 lines.append("%szlen S 2 %s %s %s" % (s, dhex(c, d), G, "00" * (nb + 1))) 228 lines.append("%sdshort S 5 %s %s %s" % (s, dhex(c, d)[2:], G, "00" * (nb - 1))) 229 lines.append("%sdlong S 5 00%s %s %s" % (s, dhex(c, d), G, "00" * (nb + 1))) 230 lines.append("%sqlen P 2 %s - %s" % (s, dhex(c, d), "00" * (2 * nb))) 231 # pair-wise consistency 232 lines.append("%spct-ok C 0 %s %s -" % (s, dhex(c, d), Q)) 233 lines.append("%spct-otherkey C 6 %s %s -" % (s, dhex(c, d + 1), Q)) 234 lines.append("%spct-offcurve C 6 %s %s -" % (s, dhex(c, d), Q[:-2] + "%02x" % (int(Q[-2:], 16) ^ 1))) 235 lines.append("%spct-d0 C 6 %s %s -" % (s, dhex(c, 0), Q)) 236 lines.append("%spct-len C 2 %s %s -" % (s, dhex(c, d), Q[:-2])) 237 with open(os.path.join(out, "edge.txt"), "w") as f: 238 f.write("# edge cases from the reference in gen_vectors.py: scalar range (0, n-1, n, n+1, 2^8nb-1),\n") 239 f.write("# peer encodings refused (infinity 00, compressed, hybrid, coordinate = p, off curve), -G,\n") 240 f.write("# buffer lengths, pair-wise consistency\n") 241 f.write("\n".join(lines) + "\n") 242 return len(lines) 243 244 245 def sha(path): 246 return hashlib.sha256(open(path, "rb").read()).hexdigest() 247 248 249 def main(): 250 wdir, zpath, out = sys.argv[1:4] 251 os.makedirs(out, exist_ok=True) 252 counts = {"cavp": cavp(zpath, out)} 253 skipped = {} 254 for c in (256, 384): 255 counts["ecpoint-%d" % c] = wy_ecpoint(wdir, c, out) 256 counts["spki-%d" % c] = wy_asn(wdir, c, out, skipped) 257 counts["edge"] = edge(out) 258 with open(os.path.join(out, "NOT_RUN.txt"), "w") as f: 259 f.write("# Wycheproof `d17cc89f` ecdh_* cases not converted, by file and flag set. Reason: the key is\n") 260 f.write("# not the standard named-curve SPKI of the file's curve (other curve OID, explicit or\n") 261 f.write("# missing parameters, compressed point or malformed ASN.1); the SPKI/ASN.1 layer is not in\n") 262 f.write("# ecdh.om, whose input is the raw TLS key_share point. Other Wycheproof ecdh files (other\n") 263 f.write("# curves, pem, webcrypto) are not converted: the approved groups are secp256r1 and secp384r1.\n") 264 for k in sorted(skipped): 265 f.write("NOT_RUN wycheproof %s: %d\n" % (k, skipped[k])) 266 print(" ".join("%s=%d" % kv for kv in sorted(counts.items()))) 267 268 269 if __name__ == "__main__": 270 main()