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 / sha2 / gen_vectors.py

162 lines · 7208 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 upstream vector sources into the
4# flat record files driver.om reads, and computes the generated long-message digests with hashlib as
5# an independent oracle. Usage, from the omega-mv root:
6# python3 om/tls/test/sha2/gen_vectors.py /tmp/wycheproof
7# Inputs: vectors/rfc4231.txt, vectors/rfc5869.txt (RFC texts, copied verbatim from rfc-editor.org),
8# WYCHEPROOF/testvectors_v1/{hmac,hkdf}_sha{256,384,512}_test.json. NIST SHAVS .rsp files are
9# converted by run.sh itself.
10import hashlib
11import hmac
12import json
13import os
14import re
15import subprocess
16import sys
17
18HERE = os.path.dirname(os.path.abspath(__file__))
19VEC = os.path.join(HERE, "vectors")
20
21
22def sha256_file(p):
23 return hashlib.sha256(open(p, "rb").read()).hexdigest()
24
25
26def hx(s):
27 return s if s else "-"
28
29
30def rfc_fields(text, start, stop):
31 """Hex fields of one test-case section: name -> hex string (continuation lines joined)."""
32 s = text.rindex(start) # the last occurrence: the first is the table of contents
33 sec = text[s:text.index(stop, s)] if stop else text[s:]
34 out, cur = {}, None
35 for line in sec.splitlines():
36 m = re.match(r"^ (\w[\w-]*)\s*=?\s+(?:0x)?([0-9a-f]+)\b", line)
37 if m and (m.group(1) in ("Key", "Data", "IKM", "salt", "info", "PRK", "OKM")
38 or m.group(1).startswith("HMAC-SHA-")):
39 cur = m.group(1)
40 out[cur] = m.group(2)
41 continue
42 m = re.match(r"^ {10,}([0-9a-f]+)\b", line)
43 if m and cur:
44 out[cur] += m.group(1)
45 continue
46 if line.strip() == "" or line.startswith("RFC ") or line.startswith("Nystrom") \
47 or line.startswith("Krawczyk") or "\f" in line:
48 continue
49 cur = None
50 return out
51
52
53def gen_rfc4231():
54 src = os.path.join(VEC, "rfc4231.txt")
55 text = open(src).read()
56 heads = ["4.2. Test Case 1", "4.3. Test Case 2", "4.4. Test Case 3", "4.5. Test Case 4",
57 "4.6. Test Case 5", "4.7. Test Case 6", "4.8. Test Case 7", "5. Security"]
58 lines = ["# RFC 4231 HMAC-SHA-256/384/512 test cases 1-7 (case 5 truncated to 128 bits).",
59 "# source https://www.rfc-editor.org/rfc/rfc4231.txt sha256 " + sha256_file(src),
60 "# record: T alg KEY MSG TAG 1"]
61 n = 0
62 for i in range(7):
63 f = rfc_fields(text, heads[i], heads[i + 1])
64 key, data = bytes.fromhex(f["Key"]), bytes.fromhex(f["Data"])
65 for alg in (256, 384, 512):
66 tag = f["HMAC-SHA-%d" % alg]
67 full = hmac.new(key, data, "sha%d" % alg).hexdigest()
68 assert full.startswith(tag), (i + 1, alg) # parser check against hashlib
69 assert (i == 4) == (len(tag) < len(full)), (i + 1, alg)
70 lines.append("T %d %s %s %s 1" % (alg, f["Key"], f["Data"], tag))
71 n += 1
72 open(os.path.join(VEC, "rfc4231-hmac.txt"), "w").write("\n".join(lines) + "\n")
73 return n
74
75
76def gen_rfc5869():
77 src = os.path.join(VEC, "rfc5869.txt")
78 text = open(src).read()
79 heads = ["A.1. Test Case 1", "A.2. Test Case 2", "A.3. Test Case 3", "A.4. Test Case 4"]
80 lines = ["# RFC 5869 HKDF-SHA-256 test cases 1-3 (A.1-A.3; A.4-A.7 are SHA-1, not implemented).",
81 "# source https://www.rfc-editor.org/rfc/rfc5869.txt sha256 " + sha256_file(src),
82 "# records: P alg SALT IKM PRK, X alg SALT IKM INFO L OKM 1"]
83 n = 0
84 for i in range(3):
85 f = rfc_fields(text, heads[i], heads[i + 1])
86 salt, info = f.get("salt", ""), f.get("info", "")
87 ikm, prk, okm = f["IKM"], f["PRK"], f["OKM"]
88 k = hmac.new(bytes.fromhex(salt) if salt else b"\0" * 32, bytes.fromhex(ikm), "sha256").hexdigest()
89 assert k == prk, i + 1
90 lines.append("P 256 %s %s %s" % (hx(salt), ikm, prk))
91 lines.append("X 256 %s %s %s %d %s 1" % (hx(salt), ikm, hx(info), len(okm) // 2, okm))
92 n += 2
93 open(os.path.join(VEC, "rfc5869-hkdf.txt"), "w").write("\n".join(lines) + "\n")
94 return n
95
96
97def wy_header(wy, names):
98 rev = subprocess.run(["git", "-C", wy, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
99 out = ["# Wycheproof (C2SP/wycheproof, Apache-2.0, LICENSE beside this file) commit " + rev]
100 for nm in names:
101 out.append("# %s sha256 %s" % (nm, sha256_file(os.path.join(wy, "testvectors_v1", nm))))
102 return out
103
104
105def gen_wy_hmac(wy):
106 names = ["hmac_sha%d_test.json" % a for a in (256, 384, 512)]
107 lines = wy_header(wy, names) + ["# record: T alg KEY MSG TAG V (V 1 valid, 0 invalid; TAG = tagSize/8 bytes)"]
108 cnt = {}
109 for alg, nm in zip((256, 384, 512), names):
110 d = json.load(open(os.path.join(wy, "testvectors_v1", nm)))
111 for g in d["testGroups"]:
112 for t in g["tests"]:
113 assert len(t["tag"]) * 4 == g["tagSize"]
114 r = t["result"]
115 assert r in ("valid", "invalid"), r
116 cnt[(alg, r)] = cnt.get((alg, r), 0) + 1
117 lines.append("T %d %s %s %s %d" % (alg, hx(t["key"]), hx(t["msg"]), t["tag"], r == "valid"))
118 open(os.path.join(VEC, "wycheproof-hmac.txt"), "w").write("\n".join(lines) + "\n")
119 return cnt
120
121
122def gen_wy_hkdf(wy):
123 names = ["hkdf_sha%d_test.json" % a for a in (256, 384, 512)]
124 lines = wy_header(wy, names) + ["# record: X alg SALT IKM INFO L OKM V (V 0 = expand must refuse)"]
125 cnt = {}
126 for alg, nm in zip((256, 384, 512), names):
127 d = json.load(open(os.path.join(wy, "testvectors_v1", nm)))
128 for g in d["testGroups"]:
129 for t in g["tests"]:
130 r = t["result"]
131 assert r in ("valid", "invalid"), r
132 if r == "invalid":
133 assert t["size"] > 255 * alg // 8, t["tcId"]
134 cnt[(alg, r)] = cnt.get((alg, r), 0) + 1
135 lines.append("X %d %s %s %s %d %s %d" % (alg, hx(t["salt"]), hx(t["ikm"]), hx(t["info"]),
136 t["size"], hx(t["okm"]), r == "valid"))
137 open(os.path.join(VEC, "wycheproof-hkdf.txt"), "w").write("\n".join(lines) + "\n")
138 return cnt
139
140
141def gen_long():
142 lines = ["# Generated messages: byte i = (7 i + 3) mod 256, streamed by driver.om in random chunks.",
143 "# Expected digests from python3 hashlib " + sys.version.split()[0] + " (independent oracle).",
144 "# record: G alg N MD"]
145 sizes = [0, 1, 55, 56, 111, 112, 127, 128, 1000003, 16777216, 16777259]
146 n = 0
147 for size in sizes:
148 msg = bytes((7 * i + 3) & 255 for i in range(size))
149 for alg in (256, 384, 512):
150 lines.append("G %d %d %s" % (alg, size, hashlib.new("sha%d" % alg, msg).hexdigest()))
151 n += 1
152 open(os.path.join(VEC, "generated-long.txt"), "w").write("\n".join(lines) + "\n")
153 return n
154
155
156if __name__ == "__main__":
157 wy = sys.argv[1] if len(sys.argv) > 1 else "/tmp/wycheproof"
158 print("rfc4231", gen_rfc4231())
159 print("rfc5869", gen_rfc5869())
160 print("wycheproof-hmac", gen_wy_hmac(wy))
161 print("wycheproof-hkdf", gen_wy_hkdf(wy))
162 print("generated-long", gen_long())