omnet
aien-dev/omnet
Brought by drakestapleton
omnet / om / ed25519 / test / gen / vectors.py
| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | """Regenerate the static vector files of om/ed25519/test/vectors/ (test tooling only). |
| 3 | |
| 4 | Usage: python3 vectors.py SRC ORACLE OUT |
| 5 | SRC directory holding the pinned upstream files (pinned URLs in om/ed25519/README.md): |
| 6 | rfc8032.txt, zip215_test.go, ed25519_test.json, and the upstream licenses |
| 7 | ed25519consensus.LICENSE and wycheproof.LICENSE (copied verbatim to OUT as |
| 8 | zip215.LICENSE and wycheproof.LICENSE; OUT/rfc8032.NOTICE is cut from the RFC's own |
| 9 | Copyright Notice section) |
| 10 | ORACLE the Go referee built from gen/oracle (reads "PK SIG MSG" lines, prints "S C") |
| 11 | OUT output directory (om/ed25519/test/vectors) |
| 12 | |
| 13 | Line format written (read by test/driver.om): ES EC PKHEX SIGHEX MSGHEX, ES/EC the expected strict |
| 14 | and consensus results (0, 1, or - to skip). Lines starting with # are comments. |
| 15 | """ |
| 16 | import hashlib |
| 17 | import json |
| 18 | import os |
| 19 | import random |
| 20 | import re |
| 21 | import shutil |
| 22 | import subprocess |
| 23 | import sys |
| 24 | |
| 25 | P = 2**255 - 19 |
| 26 | L = 2**252 + 27742317777372353535851937790883648493 |
| 27 | |
| 28 | |
| 29 | def sha256(path): |
| 30 | return hashlib.sha256(open(path, "rb").read()).hexdigest() |
| 31 | |
| 32 | |
| 33 | def oracle(exe, cases): |
| 34 | """cases: list of (pk, sig, msg) bytes; returns list of (strict, consensus) ints from Go.""" |
| 35 | data = "".join(f"{pk.hex()} {sig.hex()} {msg.hex()}\n" for pk, sig, msg in cases) |
| 36 | out = subprocess.run([exe], input=data.encode(), capture_output=True, check=True).stdout |
| 37 | res = [tuple(int(x) for x in line.split()) for line in out.decode().splitlines()] |
| 38 | assert len(res) == len(cases) |
| 39 | return res |
| 40 | |
| 41 | |
| 42 | def line(es, ec, pk, sig, msg): |
| 43 | return f"{es} {ec} {pk.hex()} {sig.hex()} {msg.hex()}\n" |
| 44 | |
| 45 | |
| 46 | def flip(b, bit): |
| 47 | a = bytearray(b) |
| 48 | a[bit // 8] ^= 1 << (bit % 8) |
| 49 | return bytes(a) |
| 50 | |
| 51 | |
| 52 | def rfc(src, exe, out): |
| 53 | path = os.path.join(src, "rfc8032.txt") |
| 54 | text = open(path).read().split("\n") |
| 55 | start = text.index("7.1. Test Vectors for Ed25519") |
| 56 | end = text.index("7.2. Test Vectors for Ed25519ctx") |
| 57 | tests, cur, field = [], None, None |
| 58 | for raw in text[start:end]: |
| 59 | s = raw.strip() |
| 60 | if raw.startswith(" -----TEST"): |
| 61 | cur = {"name": s[10:], "PUBLIC KEY": "", "MESSAGE": "", "SIGNATURE": ""} |
| 62 | tests.append(cur) |
| 63 | field = None |
| 64 | continue |
| 65 | m = re.match(r"(SECRET KEY|PUBLIC KEY|MESSAGE|SIGNATURE)", s) |
| 66 | if m: |
| 67 | field = m.group(1) |
| 68 | continue |
| 69 | if s in ("ALGORITHM:", "Ed25519"): |
| 70 | field = None |
| 71 | continue |
| 72 | if cur and field and field != "SECRET KEY" and re.fullmatch(r"[0-9a-f]+", s): |
| 73 | cur[field] += s |
| 74 | assert [t["name"] for t in tests] == ["1", "2", "3", "1024", "SHA(abc)"] |
| 75 | cases, notes = [], [] |
| 76 | for t in tests: |
| 77 | pk = bytes.fromhex(t["PUBLIC KEY"]) |
| 78 | sig = bytes.fromhex(t["SIGNATURE"]) |
| 79 | msg = bytes.fromhex(t["MESSAGE"]) |
| 80 | cases.append((pk, sig, msg, 1, f"TEST {t['name']} ({len(msg)}-byte message)")) |
| 81 | # one flipped bit in R, in S, in the public key, and (if nonempty) in the message |
| 82 | cases.append((pk, flip(sig, 3), msg, 0, f"TEST {t['name']} R bit 3 flipped")) |
| 83 | cases.append((pk, flip(sig, 256 + 9), msg, 0, f"TEST {t['name']} S bit 9 flipped")) |
| 84 | cases.append((flip(pk, 17), sig, msg, 0, f"TEST {t['name']} public key bit 17 flipped")) |
| 85 | if msg: |
| 86 | cases.append((pk, sig, flip(msg, 8 * len(msg) - 1), 0, |
| 87 | f"TEST {t['name']} last message bit flipped")) |
| 88 | go = oracle(exe, [c[:3] for c in cases]) |
| 89 | with open(os.path.join(out, "rfc8032.txt"), "w") as f: |
| 90 | f.write("# RFC 8032 section 7.1 Ed25519 test vectors (TEST 1, 2, 3, 1024, SHA(abc)) and\n") |
| 91 | f.write("# one-bit-flipped variants. Source: https://www.rfc-editor.org/rfc/rfc8032.txt\n") |
| 92 | f.write(f"# sha256 {sha256(path)}. Expected: 1 for the RFC vectors, 0 for every flip\n") |
| 93 | f.write("# (Go crypto/ed25519 and ed25519consensus agree on every line).\n") |
| 94 | f.write("# Keys, messages and signatures are from RFC 8032, Copyright (c) 2017 IETF Trust and the\n") |
| 95 | f.write("# persons identified as the document authors (S. Josefsson, I. Liusvaara); see\n") |
| 96 | f.write("# rfc8032.NOTICE. Converted to this line format (and bit flips added) by gen/vectors.py.\n") |
| 97 | for (pk, sig, msg, exp, name), g in zip(cases, go): |
| 98 | assert g == (exp, exp), (name, g) |
| 99 | f.write(f"# {name}\n") |
| 100 | f.write(line(exp, exp, pk, sig, msg)) |
| 101 | return len(cases) |
| 102 | |
| 103 | |
| 104 | def zip215(src, exe, out): |
| 105 | path = os.path.join(src, "zip215_test.go") |
| 106 | body = open(path).read() |
| 107 | pairs = re.findall(r'\{\s*"([0-9a-f]{64})",\s*"([0-9a-f]{128})",\s*\}', body) |
| 108 | assert len(pairs) == 196, len(pairs) |
| 109 | msg = b"Zcash" |
| 110 | cases = [(bytes.fromhex(a), bytes.fromhex(b), msg) for a, b in pairs] |
| 111 | go = oracle(exe, cases) |
| 112 | ns = sum(g[0] for g in go) |
| 113 | with open(os.path.join(out, "zip215.txt"), "w") as f: |
| 114 | f.write("# ZIP 215 small-order / non-canonical cases, message \"Zcash\" (196 = 14 A x 14 R\n") |
| 115 | f.write("# encodings, S = 0). Source: github.com/hdevalence/ed25519consensus zip215_test.go at\n") |
| 116 | f.write("# commit 15731de461e4d21d6a79d5b7aaf473454f9d2009 (tag v0.2.0),\n") |
| 117 | f.write(f"# sha256 {sha256(path)}. Consensus expected 1 for all 196 (TestZIP215).\n") |
| 118 | f.write("# Strict expected = Go 1.26.0 crypto/ed25519.Verify, run as referee " |
| 119 | f"({ns} of 196 accepted).\n") |
| 120 | f.write("# The key and signature hex strings are copied from that file (header: Copyright 2016\n") |
| 121 | f.write("# Henry de Valence. All rights reserved. Use of this source code is governed by a\n") |
| 122 | f.write("# BSD-style license). Redistributed under that license, included verbatim as\n") |
| 123 | f.write("# zip215.LICENSE (Copyright (c) 2009 The Go Authors; Copyright (c) 2020 Henry de\n") |
| 124 | f.write("# Valence). Converted to this line format by gen/vectors.py.\n") |
| 125 | for (pk, sig, m), g in zip(cases, go): |
| 126 | assert g[1] == 1 |
| 127 | f.write(line(g[0], 1, pk, sig, m)) |
| 128 | return len(cases), ns |
| 129 | |
| 130 | |
| 131 | def wycheproof(src, exe, out): |
| 132 | path = os.path.join(src, "ed25519_test.json") |
| 133 | d = json.load(open(path)) |
| 134 | cases, skipped = [], [] |
| 135 | for g in d["testGroups"]: |
| 136 | pk = bytes.fromhex(g["publicKey"]["pk"]) |
| 137 | for t in g["tests"]: |
| 138 | sig = bytes.fromhex(t["sig"]) |
| 139 | msg = bytes.fromhex(t["msg"]) |
| 140 | if len(sig) != 64: |
| 141 | assert t["result"] == "invalid" |
| 142 | skipped.append(t["tcId"]) |
| 143 | continue |
| 144 | cases.append((pk, sig, msg, t)) |
| 145 | go = oracle(exe, [c[:3] for c in cases]) |
| 146 | acc = [] |
| 147 | with open(os.path.join(out, "wycheproof.txt"), "w") as f: |
| 148 | f.write("# Wycheproof ed25519_test.json, https://github.com/C2SP/wycheproof/blob/\n") |
| 149 | f.write("# a3d5d1423f2592d6646836a45a21a1b209da9f4d/testvectors_v1/ed25519_test.json\n") |
| 150 | f.write(f"# sha256 {sha256(path)}. Strict expected = Wycheproof result for valid/invalid\n") |
| 151 | f.write("# (Go 1.26.0 crypto/ed25519 agrees on each), and Go's result for 'acceptable'.\n") |
| 152 | f.write("# Consensus expected = ed25519consensus v0.2.0 run as referee. Signatures that are not\n") |
| 153 | f.write(f"# 64 bytes long cannot be passed to edverify (tcId {', '.join(map(str, skipped))};\n") |
| 154 | f.write("# all 'invalid'; Go rejects them by length).\n") |
| 155 | f.write("# Copyright 2016-2026 The Wycheproof Authors, licensed under the Apache License 2.0\n") |
| 156 | f.write("# (wycheproof.LICENSE, upstream LICENSE verbatim). Modified: converted from JSON to\n") |
| 157 | f.write("# this line format by gen/vectors.py; tests with signatures not 64 bytes left out.\n") |
| 158 | for (pk, sig, msg, t), g in zip(cases, go): |
| 159 | if t["result"] == "valid": |
| 160 | assert g[0] == 1, t["tcId"] |
| 161 | elif t["result"] == "invalid": |
| 162 | assert g[0] == 0, t["tcId"] |
| 163 | else: |
| 164 | acc.append((t["tcId"], g[0], g[1])) |
| 165 | f.write(f"# tcId {t['tcId']} {t['result']} {' '.join(t['flags'])}\n") |
| 166 | f.write(line(g[0], g[1], pk, sig, msg)) |
| 167 | return len(cases), skipped, acc |
| 168 | |
| 169 | |
| 170 | def edge(exe, out): |
| 171 | """Go-refereed edge corpus: signatures from the pure-Python RFC 8032 signer below (seed fixed), |
| 172 | pushed to the corners where strict and consensus differ.""" |
| 173 | rnd = random.Random(20261025) |
| 174 | small = small_order_encodings() |
| 175 | cases = [] |
| 176 | for i in range(400): |
| 177 | sk = rnd.randbytes(32) |
| 178 | msg = rnd.randbytes(rnd.randrange(0, 200)) |
| 179 | kind = i % 8 |
| 180 | if kind == 1: # R + small-order point, hashed as sent: consensus accepts, strict rejects |
| 181 | pk, sig = sign(sk, msg, tr=rnd.randrange(1, 8)) |
| 182 | elif kind == 2: # A + small-order point: consensus accepts, strict iff [k]T = 0 |
| 183 | pk, sig = sign(sk, msg, ta=rnd.randrange(1, 8)) |
| 184 | elif kind == 3: # both torsioned |
| 185 | pk, sig = sign(sk, msg, tr=rnd.randrange(1, 8), ta=rnd.randrange(1, 8)) |
| 186 | else: |
| 187 | pk, sig = sign(sk, msg) |
| 188 | if kind == 0: # S + L (S >= L is rejected in both modes) |
| 189 | s = int.from_bytes(sig[32:], "little") + L |
| 190 | sig = sig[:32] + s.to_bytes(32, "little") |
| 191 | elif kind == 4: # small-order A and R (canonical or not), S = 0, random message |
| 192 | pk = rnd.choice(small) |
| 193 | sig = rnd.choice(small) + bytes(32) |
| 194 | elif kind == 5: # random 32 bytes as A |
| 195 | pk = rnd.randbytes(32) |
| 196 | elif kind == 6: # random 32 bytes as R |
| 197 | sig = rnd.randbytes(32) + sig[32:] |
| 198 | elif kind == 7: # one of the top three bits of S set |
| 199 | sig = sig[:63] + bytes([sig[63] | (32 << rnd.randrange(0, 3))]) |
| 200 | cases.append((pk, sig, msg)) |
| 201 | go = oracle(exe, cases) |
| 202 | with open(os.path.join(out, "edge.txt"), "w") as f: |
| 203 | f.write("# Edge corpus (400 cases, generated by gen/vectors.py, seed 20261025): RFC 8032\n") |
| 204 | f.write("# signatures with S + L, torsioned R and/or A (hashed as sent), small-order A and R\n") |
| 205 | f.write("# with S = 0, random A or R bytes, high S bits. Expected = Go 1.26.0\n") |
| 206 | f.write("# crypto/ed25519.Verify (strict) and ed25519consensus v0.2.0 (consensus), run as referees.\n") |
| 207 | for (pk, sig, msg), g in zip(cases, go): |
| 208 | f.write(line(g[0], g[1], pk, sig, msg)) |
| 209 | return len(cases), sum(g[0] for g in go), sum(g[1] for g in go) |
| 210 | |
| 211 | |
| 212 | # --- pure-Python Ed25519 reference (RFC 8032 section 5.1, test-time generator only) --- |
| 213 | D = -121665 * pow(121666, P - 2, P) % P |
| 214 | I = pow(2, (P - 1) // 4, P) |
| 215 | |
| 216 | |
| 217 | def padd(p, q): |
| 218 | x1, y1, z1, t1 = p |
| 219 | x2, y2, z2, t2 = q |
| 220 | a = (y1 - x1) * (y2 - x2) % P |
| 221 | b = (y1 + x1) * (y2 + x2) % P |
| 222 | c = 2 * t1 * t2 * D % P |
| 223 | d = 2 * z1 * z2 % P |
| 224 | e, f, g, h = b - a, d - c, d + c, b + a |
| 225 | return (e * f % P, g * h % P, f * g % P, e * h % P) |
| 226 | |
| 227 | |
| 228 | def pmul(s, p): |
| 229 | q = (0, 1, 1, 0) |
| 230 | while s: |
| 231 | if s & 1: |
| 232 | q = padd(q, p) |
| 233 | p = padd(p, p) |
| 234 | s >>= 1 |
| 235 | return q |
| 236 | |
| 237 | |
| 238 | def penc(p): |
| 239 | x, y, z, _ = p |
| 240 | zi = pow(z, P - 2, P) |
| 241 | x, y = x * zi % P, y * zi % P |
| 242 | return (y | ((x & 1) << 255)).to_bytes(32, "little") |
| 243 | |
| 244 | |
| 245 | def pdec(b): |
| 246 | y = int.from_bytes(b, "little") |
| 247 | sign = y >> 255 |
| 248 | y &= (1 << 255) - 1 |
| 249 | y %= P |
| 250 | u, v = (y * y - 1) % P, (D * y * y + 1) % P |
| 251 | x = u * pow(v, 3, P) * pow(u * pow(v, 7, P), (P - 5) // 8, P) % P |
| 252 | if v * x * x % P == u: |
| 253 | pass |
| 254 | elif v * x * x % P == (-u) % P: |
| 255 | x = x * I % P |
| 256 | else: |
| 257 | return None |
| 258 | if (x & 1) != sign: |
| 259 | x = (-x) % P |
| 260 | return (x, y, 1, x * y % P) |
| 261 | |
| 262 | |
| 263 | BY = 4 * pow(5, P - 2, P) % P |
| 264 | BASE = pdec(BY.to_bytes(32, "little")) |
| 265 | |
| 266 | |
| 267 | def sign(sk, msg, tr=0, ta=0): |
| 268 | """RFC 8032 section 5.1.6 signing; tr/ta add [tr]T / [ta]T (T of order 8) to R / A before |
| 269 | they are encoded and hashed, so the cofactored equation still holds.""" |
| 270 | h = hashlib.sha512(sk).digest() |
| 271 | a = int.from_bytes(h[:32], "little") |
| 272 | a &= (1 << 254) - 8 |
| 273 | a |= 1 << 254 |
| 274 | pk = penc(padd(pmul(a, BASE), pmul(ta, T8))) |
| 275 | r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little") % L |
| 276 | rb = penc(padd(pmul(r, BASE), pmul(tr, T8))) |
| 277 | k = int.from_bytes(hashlib.sha512(rb + pk + msg).digest(), "little") % L |
| 278 | s = (r + k * a) % L |
| 279 | return pk, rb + s.to_bytes(32, "little") |
| 280 | |
| 281 | |
| 282 | def torsion8(): |
| 283 | """A point of order 8: [L]Q for the first decodable small y whose [4][L]Q is not the identity.""" |
| 284 | ident = penc((0, 1, 1, 0)) |
| 285 | for y in range(2, 1000): |
| 286 | q = pdec(y.to_bytes(32, "little")) |
| 287 | if q is None: |
| 288 | continue |
| 289 | t = pmul(L, q) |
| 290 | if penc(pmul(4, t)) != ident: |
| 291 | return t |
| 292 | raise AssertionError("no point of order 8 found") |
| 293 | |
| 294 | |
| 295 | T8 = torsion8() |
| 296 | |
| 297 | |
| 298 | def small_order_encodings(): |
| 299 | """The 8 small-order points (canonical encodings), their non-canonical y + p forms where |
| 300 | y + p < 2^255, and x = 0 points with the sign bit set.""" |
| 301 | out = [penc(pmul(k, T8)) for k in range(8)] |
| 302 | extra = [] |
| 303 | for e in out: |
| 304 | v = int.from_bytes(e, "little") |
| 305 | y = v & ((1 << 255) - 1) |
| 306 | if y + P < 2**255: |
| 307 | extra.append(((y + P) | (v >> 255 << 255)).to_bytes(32, "little")) |
| 308 | if y in (1, P - 1): # x = 0 points: set the sign bit too |
| 309 | extra.append((y | (1 << 255)).to_bytes(32, "little")) |
| 310 | return out + extra |
| 311 | |
| 312 | |
| 313 | def notices(src, out): |
| 314 | """Third-party notices that must travel with the copied vectors.""" |
| 315 | for name, dst in (("ed25519consensus.LICENSE", "zip215.LICENSE"), |
| 316 | ("wycheproof.LICENSE", "wycheproof.LICENSE")): |
| 317 | shutil.copyfile(os.path.join(src, name), os.path.join(out, dst)) |
| 318 | text = open(os.path.join(src, "rfc8032.txt")).read().split("\n") |
| 319 | a = text.index("Copyright Notice") |
| 320 | b = next(i for i in range(a + 1, len(text)) if text[i - 1].strip().endswith("to this document.")) |
| 321 | with open(os.path.join(out, "rfc8032.NOTICE"), "w") as f: |
| 322 | f.write("The keys, messages and signatures in rfc8032.txt are copied from RFC 8032\n") |
| 323 | f.write("(https://www.rfc-editor.org/rfc/rfc8032.txt), section 7.1. Its notice, verbatim:\n\n") |
| 324 | f.write("\n".join(text[a:b]) + "\n") |
| 325 | |
| 326 | |
| 327 | def main(): |
| 328 | src, exe, out = sys.argv[1:4] |
| 329 | os.makedirs(out, exist_ok=True) |
| 330 | notices(src, out) |
| 331 | print("rfc8032", rfc(src, exe, out)) |
| 332 | print("zip215 cases, strict-accepted", zip215(src, exe, out)) |
| 333 | n, skipped, acc = wycheproof(src, exe, out) |
| 334 | print("wycheproof cases", n, "skipped (length)", skipped) |
| 335 | print("acceptable (tcId, go strict, consensus)", acc) |
| 336 | print("edge cases, strict-accepted, consensus-accepted", edge(exe, out)) |
| 337 | |
| 338 | |
| 339 | if __name__ == "__main__": |
| 340 | main() |