"""Extract the five Ed25519 test vectors of RFC 8032 section 7.1 into JSON. Usage: python -I extract_rfc8032.py PATH/rfc8032.txt OUT.json PATH/rfc8032.txt is https://www.rfc-editor.org/rfc/rfc8032.txt, unchanged (its sha256 is pinned below and in SOURCES.md). Page breaks are skipped; every hex field is joined as printed, and the message length is checked against the "(length N bytes)" the RFC states. """ import hashlib import json import re import sys PINNED = "ed63657ff389301282b169b0abde9b5dd2c7e4d524fdfa5da6ff3094fc93c4c3" FIELDS = {"SECRET KEY:": "secret_key", "PUBLIC KEY:": "public_key", "SIGNATURE:": "signature"} def main(): src, out = sys.argv[1], sys.argv[2] raw = open(src, "rb").read() got = hashlib.sha256(raw).hexdigest() if got != PINNED: raise SystemExit(f"{src}: sha256 {got} is not the pinned {PINNED}") lines = raw.decode("ascii").splitlines() start = lines.index("7.1. Test Vectors for Ed25519") end = lines.index("7.2. Test Vectors for Ed25519ctx") tests, cur, field, declared = [], None, None, None for line in lines[start:end]: s = line.strip() if s.startswith("Josefsson & Liusvaara") or s.startswith("RFC 8032 ") or s == "\f" or s == "": continue if s.startswith("-----TEST "): cur = {"name": s[len("-----TEST "):], "secret_key": "", "public_key": "", "message": "", "signature": ""} tests.append(cur) field = None continue if cur is None or s == "-----": continue m = re.fullmatch(r"MESSAGE \(length (\d+) bytes?\):", s) if m: field, declared = "message", int(m.group(1)) cur["_declared"] = declared continue if s in FIELDS: field = FIELDS[s] continue if s in ("ALGORITHM:", "Ed25519"): field = None continue if field and re.fullmatch(r"[0-9a-f]+", s): cur[field] += s continue raise SystemExit(f"unexpected line in section 7.1: {line!r}") for t in tests: n = t.pop("_declared") if len(t["message"]) != 2 * n: raise SystemExit(f"TEST {t['name']}: message is {len(t['message']) // 2} bytes, RFC says {n}") for k, size in (("secret_key", 32), ("public_key", 32), ("signature", 64)): if len(t[k]) != 2 * size: raise SystemExit(f"TEST {t['name']}: {k} is not {size} bytes") if [t["name"] for t in tests] != ["1", "2", "3", "1024", "SHA(abc)"]: raise SystemExit(f"unexpected tests: {[t['name'] for t in tests]}") doc = {"source": "RFC 8032 section 7.1, https://www.rfc-editor.org/rfc/rfc8032.txt", "tests": tests} with open(out, "w", encoding="utf-8", newline="\n") as f: json.dump(doc, f, indent=2) f.write("\n") print(f"{out}: {len(tests)} vectors") if __name__ == "__main__": main()