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 / chacha / gen_rfc.py

208 lines · 8046 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3# gen_rfc.py: test tooling only. Converts the test vectors of RFC 8439 (vectors/rfc8439.txt, a
4# byte copy of https://www.rfc-editor.org/rfc/rfc8439.txt) into driver records (see driver.om).
5# Hex dumps ("000 4c 61 ...", "02 00 ...", "9f:7b:...") are read mechanically from the RFC text.
6# Values that the RFC prints inline (keys in "Key = 00:01:..", state matrices, r/s strings) are
7# written below and each one is checked to occur, as a hex string, in the RFC section it is cited
8# from, with whitespace and colons removed; a value not found aborts the conversion.
9# Usage: python3 gen_rfc.py vectors/rfc8439.txt > vectors/rfc8439-vectors.txt
10import re
11import sys
12
13LINES = open(sys.argv[1], encoding="ascii").read().split("\n")
14DUMP = re.compile(r"^\s*\d{3} ((?:[0-9a-f]{2} ?){1,16})")
15PLAIN = re.compile(r"^\s*((?:[0-9A-F]{2} ){15}[0-9A-F]{2})\s*$")
16COLON = re.compile(r"^\s*([0-9a-f]{2}(?::[0-9a-f]{2})+):?\s*$")
17out = []
18
19
20def heading(text):
21 for i, line in enumerate(LINES):
22 if line.startswith(text):
23 return i
24 sys.exit("heading not found: " + text)
25
26
27def section(start, stop):
28 return LINES[heading(start):heading(stop)]
29
30
31def norm(lines):
32 return re.sub(r"[\s:*]", "", "\n".join(lines)).lower()
33
34
35def lit(lines, hexstr):
36 h = hexstr.replace(" ", "").replace(":", "").lower()
37 if h not in norm(lines):
38 sys.exit("literal not found in its RFC section: " + hexstr)
39 return h
40
41
42def data(line):
43 m = DUMP.match(line)
44 if m:
45 return m.group(1).split()
46 m = PLAIN.match(line)
47 if m:
48 return m.group(1).lower().split()
49 m = COLON.match(line)
50 if m:
51 return m.group(1).split(":")
52 return None
53
54
55def labelled(lines):
56 # the hex bytes under each label line ("Key:", "Tag:", "The ChaCha20 Key", ...); a label seen
57 # again starts over, so the caller reads one test vector's lines at a time
58 vals, cur = {}, None
59 for line in lines:
60 s = line.strip()
61 if s.startswith("Nir & Langley") or s.startswith("RFC 8439 ") or s.startswith("\f"):
62 continue
63 d = data(line)
64 if d is not None:
65 if cur is not None:
66 vals[cur] = vals.get(cur, "") + "".join(d)
67 continue
68 m = re.match(r"^(?:Initial )?Block Counter = (\d+)$", s)
69 if m:
70 vals["counter"] = m.group(1)
71 cur = None
72 elif s.endswith(":") or s == "The ChaCha20 Key":
73 cur = s.rstrip(":")
74 vals[cur] = ""
75 elif s:
76 cur = cur if cur is not None and s.startswith("=") else None
77 return vals
78
79
80def vectors(lines):
81 # split an appendix section at "Test Vector #n"
82 starts = [i for i, l in enumerate(lines) if re.match(r"^\s*Test Vector #\d+", l)]
83 starts.append(len(lines))
84 return [lines[starts[i]:starts[i + 1]] for i in range(len(starts) - 1)]
85
86
87def words(lines, text):
88 # a 4x4 state printed as eight-digit words, checked against the section
89 return lit(lines, text)
90
91
92def rec(*fields):
93 out.append(" ".join(f if f != "" else "-" for f in map(str, fields)))
94
95
96def note(text):
97 out.append("# " + text)
98
99
100def zeros(n):
101 return "00" * n
102
103
104# 2.1.1 quarter round on a, b, c, d
105s = section("2.1.1.", "2.2. ")
106st = lit(s, "11111111") + lit(s, "01020304") + lit(s, "9b8d6f43") + lit(s, "01234567") + "0" * 96
107ex = lit(s, "ea2a92f4") + lit(s, "cb1cf8ce") + lit(s, "4581472e") + lit(s, "5881c4bb") + "0" * 96
108note("RFC 8439 2.1.1 quarter round (a, b, c, d in words 0..3)")
109rec("Q", 0, 1, 2, 3, st, ex)
110
111# 2.2.1 QUARTERROUND(2, 7, 8, 13) on a state
112s = section("2.2.1.", "2.3. ")
113st = words(s, "879531e0 c5ecf37d 516461b1 c9a62f8a 44c20ef3 3390af7f d9fc690b 2a5f714c"
114 " 53372767 b00a5631 974c541a 359e9963 5c971061 3d631689 2098d9d6 91dbd320")
115ex = words(s, "879531e0 c5ecf37d bdb886dc c9a62f8a 44c20ef3 3390af7f d9fc690b cfacafd2")
116ex2 = words(s, "e46bea80 b00a5631 974c541a 359e9963 5c971061 ccc07c79 2098d9d6 91dbd320")
117note("RFC 8439 2.2.1 QUARTERROUND(2, 7, 8, 13)")
118rec("Q", 2, 7, 8, 13, st, ex + ex2)
119
120# 2.3.2 block function
121s = section("2.3.2.", "2.4. ")
122key = lit(s, "00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f")
123nonce = lit(s, "00:00:00:09:00:00:00:4a:00:00:00:00")
124v = labelled(s)
125note("RFC 8439 2.3.2 block function, counter 1 (serialized block = keystream)")
126rec("C", key + nonce, 1, zeros(64), v["Serialized Block"], 0)
127
128# 2.4.2 encryption
129s = section("2.4.2.", "2.5. ")
130nonce = lit(s, "00:00:00:00:00:00:00:4a:00:00:00:00")
131v = labelled(s)
132note("RFC 8439 2.4.2 encryption, initial counter 1")
133rec("C", key + nonce, 1, v["Plaintext Sunscreen"], v["Ciphertext Sunscreen"], 0)
134note("RFC 8439 2.4.2 keystream")
135rec("C", key + nonce, 1, zeros(len(v["Keystream"]) // 2), v["Keystream"], 0)
136
137# 2.5.2 Poly1305
138s = section("2.5.2.", "2.6. ")
139pk = lit(s, "85:d6:be:78:57:55:6d:33:7f:44:52:fe:42:d5:06:a8:01:03:80:8a:fb:0d:b2:fd:4a:bf:f6:af:41:49:f5:1b")
140tag = lit(s, "a8:06:1d:c1:30:51:36:c6:c2:2b:8b:af:0c:01:27:a9")
141v = labelled(s)
142note("RFC 8439 2.5.2 Poly1305")
143rec("P", pk, v["Message to be Authenticated"], tag, 0)
144
145# 2.6.2 key generation: the first 32 bytes of block 0
146s = section("2.6.2.", "2.7. ")
147v = labelled(s)
148note("RFC 8439 2.6.2 Poly1305 key generation (block 0, first 32 bytes)")
149rec("C", v["Key"] + v["Nonce"], 0, zeros(32), v["Output bytes"], 0)
150
151# 2.8.2 AEAD
152s = section("2.8.2.", "3. Implementation Advice")
153v = labelled(s)
154tag = lit(s, "1a:e1:0b:59:4f:09:e2:6a:7e:90:2e:cb:d0:60:06:91")
155kn = v["Key"] + v["32-bit fixed-common part"] + v["IV"]
156note("RFC 8439 2.8.2 AEAD seal and open")
157rec("A", kn, v["AAD"], v["Plaintext"], v["Ciphertext"] + tag, 0)
158note("RFC 8439 2.8.2 one-time key (block 0)")
159rec("C", kn, 0, zeros(32), v["Poly1305 Key"], 0)
160note("RFC 8439 2.8.2 keystream from block 1")
161rec("C", kn, 1, zeros(len(v["keystream bytes"]) // 2), v["keystream bytes"], 0)
162note("RFC 8439 2.8.2 Poly1305 over the AEAD construction")
163rec("P", v["Poly1305 Key"], v["AEAD Construction for Poly1305"], tag, 0)
164
165# A.1 block functions
166for i, t in enumerate(vectors(section("A.1. ", "A.2. ")), 1):
167 v = labelled(t)
168 note("RFC 8439 A.1 test vector #%d" % i)
169 rec("C", v["Key"] + v["Nonce"], v["counter"], zeros(64), v["Keystream"], 0)
170
171# A.2 encryption
172for i, t in enumerate(vectors(section("A.2. ", "A.3. ")), 1):
173 v = labelled(t)
174 note("RFC 8439 A.2 test vector #%d" % i)
175 rec("C", v["Key"] + v["Nonce"], v["counter"], v["Plaintext"], v["Ciphertext"], 0)
176
177# A.3 Poly1305
178for i, t in enumerate(vectors(section("A.3. ", "A.4. ")), 1):
179 v = labelled(t)
180 note("RFC 8439 A.3 test vector #%d" % i)
181 if "One-time Poly1305 Key" in v:
182 rec("P", v["One-time Poly1305 Key"], v["Text to MAC"], v["Tag"], 0)
183 else:
184 rec("P", v["R"] + v["S"], v["data"], v["tag"], 0)
185
186# A.4 key generation
187for i, t in enumerate(vectors(section("A.4. ", "A.5. ")), 1):
188 v = labelled(t)
189 note("RFC 8439 A.4 test vector #%d" % i)
190 rec("C", v["The ChaCha20 Key"] + v["The nonce"], 0, zeros(32), v["Poly1305 one-time key"], 0)
191
192# A.5 AEAD decryption
193s = section("A.5. ", "Appendix B.")
194v = labelled(s)
195kn = v["The ChaCha20 Key"] + v["The nonce"]
196note("RFC 8439 A.5 AEAD decryption (and seal of the plaintext back to the same ciphertext)")
197rec("A", kn, v["The AAD"], v["Plaintext"], v["Ciphertext"] + v["Received Tag"], 0)
198note("RFC 8439 A.5 one-time key")
199rec("C", kn, 0, zeros(32), v["Poly1305 one-time key"], 0)
200note("RFC 8439 A.5 Poly1305 over the AEAD buffer")
201rec("P", v["Poly1305 one-time key"], v["Poly1305 Input"], v["Calculated Tag"], 0)
202
203sizes = {"A.5 out bytes": v["out bytes"][:64] == v["Poly1305 one-time key"]}
204if not all(sizes.values()):
205 sys.exit("A.5 out bytes disagree with the one-time key")
206print("# Converted by gen_rfc.py from vectors/rfc8439.txt (RFC 8439, https://www.rfc-editor.org/rfc/rfc8439.txt).")
207print("# Fields: see driver.om. %d records." % sum(1 for l in out if not l.startswith("#")))
208print("\n".join(out))