blob: 0377c57de9c35bc465fbb5e178a0ccd0c7662b14 [file] [log] [blame]
Alex Gaynor5951f462014-11-16 09:08:42 -08001# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
Alex Gaynorf312a5c2013-08-10 15:23:38 -04004
Alex Gaynorc37feed2014-03-08 08:32:56 -08005from __future__ import absolute_import, division, print_function
6
Alex Stapletonc387cf72014-04-13 13:58:02 +01007import binascii
Alex Gaynor36e651c2014-01-27 10:08:35 -08008import collections
Simo Sorce7600dee2015-09-22 21:56:20 -04009import math
Alex Stapletonc387cf72014-04-13 13:58:02 +010010import re
Alex Stapleton707b0082014-04-20 22:24:41 +010011from contextlib import contextmanager
Paul Kehrer90450f32014-03-19 12:37:17 -040012
Alex Stapletona39a3192014-03-14 20:03:12 +000013import pytest
14
Paul Kehrerafc1ccd2014-03-19 11:49:32 -040015import six
Alex Gaynor2b3f9422013-12-24 21:55:24 -080016
Alex Gaynor7a489db2014-03-22 15:09:34 -070017from cryptography.exceptions import UnsupportedAlgorithm
Alex Gaynor07c4dcc2014-04-05 11:22:07 -070018
Alex Stapletona39a3192014-03-14 20:03:12 +000019import cryptography_vectors
Matthew Iversen68e77c72014-03-13 08:54:43 +110020
Alex Gaynor2b3f9422013-12-24 21:55:24 -080021
Alex Gaynor36e651c2014-01-27 10:08:35 -080022HashVector = collections.namedtuple("HashVector", ["message", "digest"])
23KeyedHashVector = collections.namedtuple(
24 "KeyedHashVector", ["message", "digest", "key"]
25)
26
27
Alex Gaynore6055fb2017-06-03 22:02:50 -040028def check_backend_support(backend, item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060029 supported = item.keywords.get("supported")
Alex Gaynore6055fb2017-06-03 22:02:50 -040030 if supported:
Alex Gaynor50ebb482015-07-02 00:21:41 -040031 for mark in supported:
Alex Gaynore6055fb2017-06-03 22:02:50 -040032 if not mark.kwargs["only_if"](backend):
Alex Gaynor50ebb482015-07-02 00:21:41 -040033 pytest.skip("{0} ({1})".format(
Alex Gaynore6055fb2017-06-03 22:02:50 -040034 mark.kwargs["skip_message"], backend
Alex Gaynor50ebb482015-07-02 00:21:41 -040035 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060036
37
Alex Gaynor7a489db2014-03-22 15:09:34 -070038@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000039def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070040 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000041 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000042
Alex Stapleton85a791f2014-03-27 16:55:41 +000043 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070044
45
Paul Kehrerfdae0702014-11-27 07:50:46 -100046def load_vectors_from_file(filename, loader, mode="r"):
47 with cryptography_vectors.open_vector_file(filename, mode) as vector_file:
Alex Stapletona39a3192014-03-14 20:03:12 +000048 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060049
50
Alex Gaynord3ce7032013-11-11 14:46:20 -080051def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060052 test_data = None
53 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040054
55 for line in vector_data:
56 line = line.strip()
57
Paul Kehrer749ac5b2013-11-18 18:12:41 -060058 # Blank lines, comments, and section headers are ignored
Alex Gaynore0a879f2015-02-15 20:54:34 -080059 if not line or line.startswith("#") or (line.startswith("[") and
60 line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080061 continue
62
Paul Kehrera43b6692013-11-12 15:35:49 -060063 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060064 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060065 continue
66
Donald Stufft9e1a48b2013-08-09 00:32:30 -040067 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060068 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040069
Paul Kehrer1050ddf2014-01-27 21:04:03 -060070 # Some tests (PBKDF2) contain \0, which should be interpreted as a
71 # null character rather than literal.
72 value = value.replace("\\0", "\0")
73
Donald Stufft9e1a48b2013-08-09 00:32:30 -040074 # COUNT is a special token that indicates a new block of data
75 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060076 test_data = {}
77 data.append(test_data)
78 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -040079 # For all other tokens we simply want the name, value stored in
80 # the dictionary
81 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -060082 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -040083
Paul Kehrer749ac5b2013-11-18 18:12:41 -060084 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -040085
86
Paul Kehrer1951bf62013-09-15 12:05:43 -050087def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -050088 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -050089
90 for line in vector_data:
91 line = line.strip()
92
93 # Blank lines and comments are ignored
94 if not line or line.startswith("#"):
95 continue
96
97 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -050098 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -050099 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500100 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500101 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500102 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
103 # after a C is found the K+P+C tuple is complete
104 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700105 cryptrec_list.append({
106 "key": key,
107 "plaintext": pt,
108 "ciphertext": ct
109 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400110 else:
111 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500112 return cryptrec_list
113
114
Paul Kehrer69e06522013-10-18 17:28:39 -0500115def load_hash_vectors(vector_data):
116 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500117 key = None
118 msg = None
119 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500120
121 for line in vector_data:
122 line = line.strip()
123
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500124 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500125 continue
126
127 if line.startswith("Len"):
128 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500129 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800130 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500131 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500132 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800133 # In the NIST vectors they have chosen to represent an empty
134 # string as hex 00, which is of course not actually an empty
135 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500136 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
137 elif line.startswith("MD"):
138 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500139 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500140 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800141 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500142 key = None
143 msg = None
144 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500145 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800146 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500147 msg = None
148 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500149 else:
150 raise ValueError("Unknown line in hash vector")
151 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000152
153
154def load_pkcs1_vectors(vector_data):
155 """
156 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000157 """
158 private_key_vector = None
159 public_key_vector = None
160 attr = None
161 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600162 example_vector = None
163 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000164 vectors = []
165 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600166 if (
167 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500168 line.startswith("# OAEP Example") or
169 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600170 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600171 if example_vector:
172 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600173 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600174 example_vector[key] = hex_str
175 examples.append(example_vector)
176
177 attr = None
178 example_vector = collections.defaultdict(list)
179
Paul Kehrer3fe91502014-03-29 12:08:39 -0500180 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600181 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600182 continue
183 elif line.startswith("# Salt"):
184 attr = "salt"
185 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500186 elif line.startswith("# Seed"):
187 attr = "seed"
188 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600189 elif line.startswith("# Signature"):
190 attr = "signature"
191 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500192 elif line.startswith("# Encryption"):
193 attr = "encryption"
194 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600195 elif (
196 example_vector and
197 line.startswith("# =============================================")
198 ):
199 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600200 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600201 example_vector[key] = hex_str
202 examples.append(example_vector)
203 example_vector = None
204 attr = None
205 elif example_vector and line.startswith("#"):
206 continue
207 else:
208 if attr is not None and example_vector is not None:
209 example_vector[attr].append(line.strip())
210 continue
211
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000212 if (
213 line.startswith("# Example") or
214 line.startswith("# =============================================")
215 ):
216 if key:
217 assert private_key_vector
218 assert public_key_vector
219
220 for key, value in six.iteritems(public_key_vector):
221 hex_str = "".join(value).replace(" ", "")
222 public_key_vector[key] = int(hex_str, 16)
223
224 for key, value in six.iteritems(private_key_vector):
225 hex_str = "".join(value).replace(" ", "")
226 private_key_vector[key] = int(hex_str, 16)
227
Paul Kehrerefca2802014-02-17 20:55:13 -0600228 private_key_vector["examples"] = examples
229 examples = []
230
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000231 assert (
232 private_key_vector['public_exponent'] ==
233 public_key_vector['public_exponent']
234 )
235
236 assert (
237 private_key_vector['modulus'] ==
238 public_key_vector['modulus']
239 )
240
241 vectors.append(
242 (private_key_vector, public_key_vector)
243 )
244
245 public_key_vector = collections.defaultdict(list)
246 private_key_vector = collections.defaultdict(list)
247 key = None
248 attr = None
249
250 if private_key_vector is None or public_key_vector is None:
251 continue
252
253 if line.startswith("# Private key"):
254 key = private_key_vector
255 elif line.startswith("# Public key"):
256 key = public_key_vector
257 elif line.startswith("# Modulus:"):
258 attr = "modulus"
259 elif line.startswith("# Public exponent:"):
260 attr = "public_exponent"
261 elif line.startswith("# Exponent:"):
262 if key is public_key_vector:
263 attr = "public_exponent"
264 else:
265 assert key is private_key_vector
266 attr = "private_exponent"
267 elif line.startswith("# Prime 1:"):
268 attr = "p"
269 elif line.startswith("# Prime 2:"):
270 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600271 elif line.startswith("# Prime exponent 1:"):
272 attr = "dmp1"
273 elif line.startswith("# Prime exponent 2:"):
274 attr = "dmq1"
275 elif line.startswith("# Coefficient:"):
276 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000277 elif line.startswith("#"):
278 attr = None
279 else:
280 if key is not None and attr is not None:
281 key[attr].append(line.strip())
282 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400283
284
285def load_rsa_nist_vectors(vector_data):
286 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400287 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400288 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400289 data = []
290
291 for line in vector_data:
292 line = line.strip()
293
294 # Blank lines and section headers are ignored
295 if not line or line.startswith("["):
296 continue
297
298 if line.startswith("# Salt len:"):
299 salt_length = int(line.split(":")[1].strip())
300 continue
301 elif line.startswith("#"):
302 continue
303
304 # Build our data using a simple Key = Value format
305 name, value = [c.strip() for c in line.split("=")]
306
307 if name == "n":
308 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400309 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400310 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400311 elif name == "p":
312 p = int(value, 16)
313 elif name == "q":
314 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400315 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400316 if p is None:
317 test_data = {
318 "modulus": n,
319 "public_exponent": e,
320 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400321 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400322 "fail": False
323 }
324 else:
325 test_data = {
326 "modulus": n,
327 "p": p,
328 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400329 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400330 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400331 if salt_length is not None:
332 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400333 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400334 elif name == "e" and p is not None:
335 test_data["public_exponent"] = int(value, 16)
336 elif name == "d":
337 test_data["private_exponent"] = int(value, 16)
338 elif name == "Result":
339 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400340 # For all other tokens we simply want the name, value stored in
341 # the dictionary
342 else:
343 test_data[name.lower()] = value.encode("ascii")
344
345 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200346
347
348def load_fips_dsa_key_pair_vectors(vector_data):
349 """
350 Loads data out of the FIPS DSA KeyPair vector files.
351 """
352 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200353 # When reading_key_data is set to True it tells the loader to continue
354 # constructing dictionaries. We set reading_key_data to False during the
355 # blocks of the vectors of N=224 because we don't support it.
356 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200357 for line in vector_data:
358 line = line.strip()
359
360 if not line or line.startswith("#"):
361 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200362 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200363 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200364 elif line.startswith("[mod = L=2048, N=224"):
365 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200366 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200367 elif line.startswith("[mod = L=2048, N=256"):
368 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200369 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200370 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200371 continue
Alex Gaynor0fe7db62015-06-27 17:20:59 -0400372
373 if reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200374 if line.startswith("P"):
375 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200376 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200377 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200378 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200379 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200380 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200381 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200382 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200383 vectors.append({'p': vectors[-1]['p'],
384 'q': vectors[-1]['q'],
385 'g': vectors[-1]['g'],
386 'x': int(line.split("=")[1], 16)
387 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200388 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200389 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200390
391 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100392
393
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200394def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200395 """
396 Loads data out of the FIPS DSA SigVer vector files.
397 """
398 vectors = []
399 sha_regex = re.compile(
400 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
401 )
402 # When reading_key_data is set to True it tells the loader to continue
403 # constructing dictionaries. We set reading_key_data to False during the
404 # blocks of the vectors of N=224 because we don't support it.
405 reading_key_data = True
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200406
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200407 for line in vector_data:
408 line = line.strip()
409
410 if not line or line.startswith("#"):
411 continue
412
413 sha_match = sha_regex.match(line)
414 if sha_match:
415 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
416
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500417 if line.startswith("[mod = L=2048, N=224"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200418 reading_key_data = False
419 continue
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500420 elif line.startswith("[mod = L=2048, N=256"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200421 reading_key_data = True
422 continue
423
424 if not reading_key_data or line.startswith("[mod"):
425 continue
426
427 name, value = [c.strip() for c in line.split("=")]
428
429 if name == "P":
430 vectors.append({'p': int(value, 16),
431 'digest_algorithm': digest_algorithm})
432 elif name == "Q":
433 vectors[-1]['q'] = int(value, 16)
434 elif name == "G":
435 vectors[-1]['g'] = int(value, 16)
436 elif name == "Msg" and 'msg' not in vectors[-1]:
437 hexmsg = value.strip().encode("ascii")
438 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
439 elif name == "Msg" and 'msg' in vectors[-1]:
440 hexmsg = value.strip().encode("ascii")
441 vectors.append({'p': vectors[-1]['p'],
442 'q': vectors[-1]['q'],
443 'g': vectors[-1]['g'],
444 'digest_algorithm':
445 vectors[-1]['digest_algorithm'],
446 'msg': binascii.unhexlify(hexmsg)})
447 elif name == "X":
448 vectors[-1]['x'] = int(value, 16)
449 elif name == "Y":
450 vectors[-1]['y'] = int(value, 16)
451 elif name == "R":
452 vectors[-1]['r'] = int(value, 16)
453 elif name == "S":
454 vectors[-1]['s'] = int(value, 16)
455 elif name == "Result":
456 vectors[-1]['result'] = value.split("(")[0].strip()
457
458 return vectors
459
460
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100461# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100462_ECDSA_CURVE_NAMES = {
463 "P-192": "secp192r1",
464 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100465 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100466 "P-384": "secp384r1",
467 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100468
Alex Stapletonc387cf72014-04-13 13:58:02 +0100469 "K-163": "sect163k1",
470 "K-233": "sect233k1",
Alex Stapletonf6a1cf62015-05-03 12:16:19 +0100471 "K-256": "secp256k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100472 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100473 "K-409": "sect409k1",
474 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100475
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100476 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100477 "B-233": "sect233r1",
478 "B-283": "sect283r1",
479 "B-409": "sect409r1",
480 "B-571": "sect571r1",
481}
482
483
Alex Stapletoncf048602014-04-12 12:48:59 +0100484def load_fips_ecdsa_key_pair_vectors(vector_data):
485 """
486 Loads data out of the FIPS ECDSA KeyPair vector files.
487 """
488 vectors = []
489 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100490 for line in vector_data:
491 line = line.strip()
492
493 if not line or line.startswith("#"):
494 continue
495
Alex Stapletonc387cf72014-04-13 13:58:02 +0100496 if line[1:-1] in _ECDSA_CURVE_NAMES:
497 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100498
499 elif line.startswith("d = "):
500 if key_data is not None:
501 vectors.append(key_data)
502
503 key_data = {
504 "curve": curve_name,
505 "d": int(line.split("=")[1], 16)
506 }
507
508 elif key_data is not None:
509 if line.startswith("Qx = "):
510 key_data["x"] = int(line.split("=")[1], 16)
511 elif line.startswith("Qy = "):
512 key_data["y"] = int(line.split("=")[1], 16)
513
Paul Kehrerb60b8dd2015-08-01 19:47:22 +0100514 assert key_data is not None
515 vectors.append(key_data)
Alex Stapletoncf048602014-04-12 12:48:59 +0100516
517 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100518
519
520def load_fips_ecdsa_signing_vectors(vector_data):
521 """
522 Loads data out of the FIPS ECDSA SigGen vector files.
523 """
524 vectors = []
525
526 curve_rx = re.compile(
527 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
528 )
529
530 data = None
531 for line in vector_data:
532 line = line.strip()
533
Alex Stapletonc387cf72014-04-13 13:58:02 +0100534 curve_match = curve_rx.match(line)
535 if curve_match:
536 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
537 digest_name = "SHA-{0}".format(curve_match.group("sha"))
538
539 elif line.startswith("Msg = "):
540 if data is not None:
541 vectors.append(data)
542
543 hexmsg = line.split("=")[1].strip().encode("ascii")
544
545 data = {
546 "curve": curve_name,
547 "digest_algorithm": digest_name,
548 "message": binascii.unhexlify(hexmsg)
549 }
550
551 elif data is not None:
552 if line.startswith("Qx = "):
553 data["x"] = int(line.split("=")[1], 16)
554 elif line.startswith("Qy = "):
555 data["y"] = int(line.split("=")[1], 16)
556 elif line.startswith("R = "):
557 data["r"] = int(line.split("=")[1], 16)
558 elif line.startswith("S = "):
559 data["s"] = int(line.split("=")[1], 16)
560 elif line.startswith("d = "):
561 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100562 elif line.startswith("Result = "):
563 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100564
Paul Kehrerb60b8dd2015-08-01 19:47:22 +0100565 assert data is not None
566 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100567 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100568
569
570def load_kasvs_dh_vectors(vector_data):
571 """
572 Loads data out of the KASVS key exchange vector data
573 """
574
575 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
576
577 vectors = []
578 data = {
579 "fail_z": False,
580 "fail_agree": False
581 }
582
583 for line in vector_data:
584 line = line.strip()
585
586 if not line or line.startswith("#"):
587 continue
588
589 if line.startswith("P = "):
590 data["p"] = int(line.split("=")[1], 16)
591 elif line.startswith("Q = "):
592 data["q"] = int(line.split("=")[1], 16)
593 elif line.startswith("G = "):
594 data["g"] = int(line.split("=")[1], 16)
595 elif line.startswith("Z = "):
596 z_hex = line.split("=")[1].strip().encode("ascii")
597 data["z"] = binascii.unhexlify(z_hex)
598 elif line.startswith("XstatCAVS = "):
599 data["x1"] = int(line.split("=")[1], 16)
600 elif line.startswith("YstatCAVS = "):
601 data["y1"] = int(line.split("=")[1], 16)
602 elif line.startswith("XstatIUT = "):
603 data["x2"] = int(line.split("=")[1], 16)
604 elif line.startswith("YstatIUT = "):
605 data["y2"] = int(line.split("=")[1], 16)
606 elif line.startswith("Result = "):
607 result_str = line.split("=")[1].strip()
608 match = result_rx.match(result_str)
609
610 if match.group(1) == "F":
611 if int(match.group(2)) in (5, 10):
612 data["fail_z"] = True
613 else:
614 data["fail_agree"] = True
615
616 vectors.append(data)
617
618 data = {
619 "p": data["p"],
620 "q": data["q"],
621 "g": data["g"],
622 "fail_z": False,
623 "fail_agree": False
624 }
625
626 return vectors
Simo Sorce917addb2015-04-29 19:41:26 -0400627
628
629def load_kasvs_ecdh_vectors(vector_data):
630 """
631 Loads data out of the KASVS key exchange vector data
632 """
633
634 curve_name_map = {
635 "P-192": "secp192r1",
636 "P-224": "secp224r1",
637 "P-256": "secp256r1",
638 "P-384": "secp384r1",
639 "P-521": "secp521r1",
640 }
641
642 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
643
644 tags = []
Alex Gaynorace036d2015-09-24 20:23:08 -0400645 sets = {}
Simo Sorce917addb2015-04-29 19:41:26 -0400646 vectors = []
647
648 # find info in header
649 for line in vector_data:
650 line = line.strip()
651
652 if line.startswith("#"):
653 parm = line.split("Parameter set(s) supported:")
654 if len(parm) == 2:
655 names = parm[1].strip().split()
656 for n in names:
657 tags.append("[%s]" % n)
658 break
659
660 # Sets Metadata
661 tag = None
662 curve = None
663 for line in vector_data:
664 line = line.strip()
665
666 if not line or line.startswith("#"):
667 continue
668
669 if line in tags:
670 tag = line
671 curve = None
672 elif line.startswith("[Curve selected:"):
673 curve = curve_name_map[line.split(':')[1].strip()[:-1]]
674
675 if tag is not None and curve is not None:
676 sets[tag.strip("[]")] = curve
677 tag = None
678 if len(tags) == len(sets):
679 break
680
681 # Data
682 data = {
Alex Gaynorace036d2015-09-24 20:23:08 -0400683 "CAVS": {},
684 "IUT": {},
Simo Sorce917addb2015-04-29 19:41:26 -0400685 }
686 tag = None
687 for line in vector_data:
688 line = line.strip()
689
690 if not line or line.startswith("#"):
691 continue
692
693 if line.startswith("["):
694 tag = line.split()[0][1:]
695 elif line.startswith("COUNT = "):
Simo Sorce6e3b1552015-10-13 14:45:21 -0400696 data["COUNT"] = int(line.split("=")[1])
Simo Sorce917addb2015-04-29 19:41:26 -0400697 elif line.startswith("dsCAVS = "):
698 data["CAVS"]["d"] = int(line.split("=")[1], 16)
699 elif line.startswith("QsCAVSx = "):
700 data["CAVS"]["x"] = int(line.split("=")[1], 16)
701 elif line.startswith("QsCAVSy = "):
702 data["CAVS"]["y"] = int(line.split("=")[1], 16)
703 elif line.startswith("dsIUT = "):
704 data["IUT"]["d"] = int(line.split("=")[1], 16)
705 elif line.startswith("QsIUTx = "):
706 data["IUT"]["x"] = int(line.split("=")[1], 16)
707 elif line.startswith("QsIUTy = "):
708 data["IUT"]["y"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400709 elif line.startswith("OI = "):
710 data["OI"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400711 elif line.startswith("Z = "):
712 data["Z"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400713 elif line.startswith("DKM = "):
714 data["DKM"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400715 elif line.startswith("Result = "):
716 result_str = line.split("=")[1].strip()
717 match = result_rx.match(result_str)
718
719 if match.group(1) == "F":
720 data["fail"] = True
721 else:
722 data["fail"] = False
723 data["errno"] = int(match.group(2))
724
725 data["curve"] = sets[tag]
726
727 vectors.append(data)
728
729 data = {
Alex Gaynorace036d2015-09-24 20:23:08 -0400730 "CAVS": {},
731 "IUT": {},
Simo Sorce917addb2015-04-29 19:41:26 -0400732 }
733
734 return vectors
Simo Sorce7600dee2015-09-22 21:56:20 -0400735
736
737def load_x963_vectors(vector_data):
738 """
739 Loads data out of the X9.63 vector data
740 """
741
742 vectors = []
743
744 # Sets Metadata
745 hashname = None
Alex Gaynorace036d2015-09-24 20:23:08 -0400746 vector = {}
Simo Sorce7600dee2015-09-22 21:56:20 -0400747 for line in vector_data:
748 line = line.strip()
749
750 if line.startswith("[SHA"):
751 hashname = line[1:-1]
752 shared_secret_len = 0
753 shared_info_len = 0
754 key_data_len = 0
755 elif line.startswith("[shared secret length"):
756 shared_secret_len = int(line[1:-1].split("=")[1].strip())
757 elif line.startswith("[SharedInfo length"):
758 shared_info_len = int(line[1:-1].split("=")[1].strip())
759 elif line.startswith("[key data length"):
760 key_data_len = int(line[1:-1].split("=")[1].strip())
761 elif line.startswith("COUNT"):
762 count = int(line.split("=")[1].strip())
763 vector["hash"] = hashname
764 vector["count"] = count
Alex Gaynorace036d2015-09-24 20:23:08 -0400765 vector["shared_secret_length"] = shared_secret_len
766 vector["sharedinfo_length"] = shared_info_len
767 vector["key_data_length"] = key_data_len
Simo Sorce7600dee2015-09-22 21:56:20 -0400768 elif line.startswith("Z"):
769 vector["Z"] = line.split("=")[1].strip()
770 assert math.ceil(shared_secret_len / 8) * 2 == len(vector["Z"])
771 elif line.startswith("SharedInfo"):
772 if shared_info_len != 0:
Alex Gaynorace036d2015-09-24 20:23:08 -0400773 vector["sharedinfo"] = line.split("=")[1].strip()
774 silen = len(vector["sharedinfo"])
Simo Sorce7600dee2015-09-22 21:56:20 -0400775 assert math.ceil(shared_info_len / 8) * 2 == silen
776 elif line.startswith("key_data"):
777 vector["key_data"] = line.split("=")[1].strip()
778 assert math.ceil(key_data_len / 8) * 2 == len(vector["key_data"])
779 vectors.append(vector)
Alex Gaynorace036d2015-09-24 20:23:08 -0400780 vector = {}
Simo Sorce7600dee2015-09-22 21:56:20 -0400781
782 return vectors
Jaredcd258d52016-04-13 14:03:52 -0700783
784
785def load_nist_kbkdf_vectors(vector_data):
786 """
787 Load NIST SP 800-108 KDF Vectors
788 """
789 vectors = []
790 test_data = None
791 tag = {}
792
793 for line in vector_data:
794 line = line.strip()
795
796 if not line or line.startswith("#"):
797 continue
798
799 if line.startswith("[") and line.endswith("]"):
800 tag_data = line[1:-1]
801 name, value = [c.strip() for c in tag_data.split("=")]
802 if value.endswith('_BITS'):
803 value = int(value.split('_')[0])
804 tag.update({name.lower(): value})
805 continue
806
807 tag.update({name.lower(): value.lower()})
808 elif line.startswith("COUNT="):
809 test_data = dict()
810 test_data.update(tag)
811 vectors.append(test_data)
812 elif line.startswith("L"):
813 name, value = [c.strip() for c in line.split("=")]
814 test_data[name.lower()] = int(value)
815 else:
816 name, value = [c.strip() for c in line.split("=")]
817 test_data[name.lower()] = value.encode("ascii")
818
819 return vectors
Paul Kehrera923b002017-06-20 01:12:35 -1000820
821
822def load_ed25519_vectors(vector_data):
823 data = []
824 for line in vector_data:
825 secret_key, public_key, message, signature, _ = line.split(':')
826 # In the vectors the first element is secret key + public key
827 secret_key = secret_key[0:64]
828 # In the vectors the signature section is signature + message
829 signature = signature[0:128]
830 data.append({
831 "secret_key": secret_key,
832 "public_key": public_key,
833 "message": message,
834 "signature": signature
835 })
836 return data