blob: c810303e370893b59de9500a7f53338462e958fa [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
Alex Stapletonc387cf72014-04-13 13:58:02 +01009import re
Alex Stapleton707b0082014-04-20 22:24:41 +010010from contextlib import contextmanager
Paul Kehrer90450f32014-03-19 12:37:17 -040011
Alex Stapletona39a3192014-03-14 20:03:12 +000012import pytest
13
Paul Kehrerafc1ccd2014-03-19 11:49:32 -040014import six
Alex Gaynor2b3f9422013-12-24 21:55:24 -080015
Alex Gaynor7a489db2014-03-22 15:09:34 -070016from cryptography.exceptions import UnsupportedAlgorithm
Alex Gaynor07c4dcc2014-04-05 11:22:07 -070017
Alex Stapletona39a3192014-03-14 20:03:12 +000018import cryptography_vectors
Matthew Iversen68e77c72014-03-13 08:54:43 +110019
Alex Gaynor2b3f9422013-12-24 21:55:24 -080020
Alex Gaynor36e651c2014-01-27 10:08:35 -080021HashVector = collections.namedtuple("HashVector", ["message", "digest"])
22KeyedHashVector = collections.namedtuple(
23 "KeyedHashVector", ["message", "digest", "key"]
24)
25
26
Paul Kehrerc421e632014-01-18 09:22:21 -060027def select_backends(names, backend_list):
28 if names is None:
29 return backend_list
30 split_names = [x.strip() for x in names.split(',')]
Paul Kehreraed9e172014-01-19 12:09:27 -060031 selected_backends = []
32 for backend in backend_list:
33 if backend.name in split_names:
34 selected_backends.append(backend)
Paul Kehrerc421e632014-01-18 09:22:21 -060035
Paul Kehreraed9e172014-01-19 12:09:27 -060036 if len(selected_backends) > 0:
37 return selected_backends
Paul Kehrerc421e632014-01-18 09:22:21 -060038 else:
39 raise ValueError(
40 "No backend selected. Tried to select: {0}".format(split_names)
41 )
Paul Kehrer34c075e2014-01-13 21:52:08 -050042
43
Paul Kehrer902d8cf2014-10-25 12:22:10 -070044def skip_if_empty(backend_list, required_interfaces):
45 if not backend_list:
46 pytest.skip(
47 "No backends provided supply the interface: {0}".format(
48 ", ".join(iface.__name__ for iface in required_interfaces)
49 )
50 )
51
52
Paul Kehrer60fc8da2013-12-26 20:19:34 -060053def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060054 supported = item.keywords.get("supported")
55 if supported and "backend" in item.funcargs:
Alex Gaynorbe28a242015-07-02 00:05:49 -040056 if not all(
57 mark.kwargs["only_if"](item.funcargs["backend"])
58 for mark in supported
59 ):
Paul Kehrerf03334e2014-01-02 23:16:14 -060060 pytest.skip("{0} ({1})".format(
61 supported.kwargs["skip_message"], item.funcargs["backend"]
62 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060063 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060064 raise ValueError("This mark is only available on methods that take a "
65 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060066
67
Alex Gaynor7a489db2014-03-22 15:09:34 -070068@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000069def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070070 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000071 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000072
Alex Stapleton85a791f2014-03-27 16:55:41 +000073 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070074
75
Paul Kehrerfdae0702014-11-27 07:50:46 -100076def load_vectors_from_file(filename, loader, mode="r"):
77 with cryptography_vectors.open_vector_file(filename, mode) as vector_file:
Alex Stapletona39a3192014-03-14 20:03:12 +000078 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060079
80
Alex Gaynord3ce7032013-11-11 14:46:20 -080081def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060082 test_data = None
83 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040084
85 for line in vector_data:
86 line = line.strip()
87
Paul Kehrer749ac5b2013-11-18 18:12:41 -060088 # Blank lines, comments, and section headers are ignored
Alex Gaynore0a879f2015-02-15 20:54:34 -080089 if not line or line.startswith("#") or (line.startswith("[") and
90 line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080091 continue
92
Paul Kehrera43b6692013-11-12 15:35:49 -060093 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060094 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060095 continue
96
Donald Stufft9e1a48b2013-08-09 00:32:30 -040097 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060098 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040099
Paul Kehrer1050ddf2014-01-27 21:04:03 -0600100 # Some tests (PBKDF2) contain \0, which should be interpreted as a
101 # null character rather than literal.
102 value = value.replace("\\0", "\0")
103
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400104 # COUNT is a special token that indicates a new block of data
105 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600106 test_data = {}
107 data.append(test_data)
108 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400109 # For all other tokens we simply want the name, value stored in
110 # the dictionary
111 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600112 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400113
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600114 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400115
116
Paul Kehrer1951bf62013-09-15 12:05:43 -0500117def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500118 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500119
120 for line in vector_data:
121 line = line.strip()
122
123 # Blank lines and comments are ignored
124 if not line or line.startswith("#"):
125 continue
126
127 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500128 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500129 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500130 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500131 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500132 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
133 # after a C is found the K+P+C tuple is complete
134 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700135 cryptrec_list.append({
136 "key": key,
137 "plaintext": pt,
138 "ciphertext": ct
139 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400140 else:
141 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500142 return cryptrec_list
143
144
Paul Kehrer69e06522013-10-18 17:28:39 -0500145def load_hash_vectors(vector_data):
146 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500147 key = None
148 msg = None
149 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500150
151 for line in vector_data:
152 line = line.strip()
153
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500154 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500155 continue
156
157 if line.startswith("Len"):
158 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500159 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800160 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500161 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500162 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800163 # In the NIST vectors they have chosen to represent an empty
164 # string as hex 00, which is of course not actually an empty
165 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500166 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
167 elif line.startswith("MD"):
168 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500169 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500170 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800171 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500172 key = None
173 msg = None
174 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500175 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800176 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500177 msg = None
178 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500179 else:
180 raise ValueError("Unknown line in hash vector")
181 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000182
183
184def load_pkcs1_vectors(vector_data):
185 """
186 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000187 """
188 private_key_vector = None
189 public_key_vector = None
190 attr = None
191 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600192 example_vector = None
193 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000194 vectors = []
195 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600196 if (
197 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500198 line.startswith("# OAEP Example") or
199 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600200 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600201 if example_vector:
202 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600203 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600204 example_vector[key] = hex_str
205 examples.append(example_vector)
206
207 attr = None
208 example_vector = collections.defaultdict(list)
209
Paul Kehrer3fe91502014-03-29 12:08:39 -0500210 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600211 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600212 continue
213 elif line.startswith("# Salt"):
214 attr = "salt"
215 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500216 elif line.startswith("# Seed"):
217 attr = "seed"
218 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600219 elif line.startswith("# Signature"):
220 attr = "signature"
221 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500222 elif line.startswith("# Encryption"):
223 attr = "encryption"
224 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600225 elif (
226 example_vector and
227 line.startswith("# =============================================")
228 ):
229 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600230 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600231 example_vector[key] = hex_str
232 examples.append(example_vector)
233 example_vector = None
234 attr = None
235 elif example_vector and line.startswith("#"):
236 continue
237 else:
238 if attr is not None and example_vector is not None:
239 example_vector[attr].append(line.strip())
240 continue
241
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000242 if (
243 line.startswith("# Example") or
244 line.startswith("# =============================================")
245 ):
246 if key:
247 assert private_key_vector
248 assert public_key_vector
249
250 for key, value in six.iteritems(public_key_vector):
251 hex_str = "".join(value).replace(" ", "")
252 public_key_vector[key] = int(hex_str, 16)
253
254 for key, value in six.iteritems(private_key_vector):
255 hex_str = "".join(value).replace(" ", "")
256 private_key_vector[key] = int(hex_str, 16)
257
Paul Kehrerefca2802014-02-17 20:55:13 -0600258 private_key_vector["examples"] = examples
259 examples = []
260
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000261 assert (
262 private_key_vector['public_exponent'] ==
263 public_key_vector['public_exponent']
264 )
265
266 assert (
267 private_key_vector['modulus'] ==
268 public_key_vector['modulus']
269 )
270
271 vectors.append(
272 (private_key_vector, public_key_vector)
273 )
274
275 public_key_vector = collections.defaultdict(list)
276 private_key_vector = collections.defaultdict(list)
277 key = None
278 attr = None
279
280 if private_key_vector is None or public_key_vector is None:
281 continue
282
283 if line.startswith("# Private key"):
284 key = private_key_vector
285 elif line.startswith("# Public key"):
286 key = public_key_vector
287 elif line.startswith("# Modulus:"):
288 attr = "modulus"
289 elif line.startswith("# Public exponent:"):
290 attr = "public_exponent"
291 elif line.startswith("# Exponent:"):
292 if key is public_key_vector:
293 attr = "public_exponent"
294 else:
295 assert key is private_key_vector
296 attr = "private_exponent"
297 elif line.startswith("# Prime 1:"):
298 attr = "p"
299 elif line.startswith("# Prime 2:"):
300 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600301 elif line.startswith("# Prime exponent 1:"):
302 attr = "dmp1"
303 elif line.startswith("# Prime exponent 2:"):
304 attr = "dmq1"
305 elif line.startswith("# Coefficient:"):
306 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000307 elif line.startswith("#"):
308 attr = None
309 else:
310 if key is not None and attr is not None:
311 key[attr].append(line.strip())
312 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400313
314
315def load_rsa_nist_vectors(vector_data):
316 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400317 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400318 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400319 data = []
320
321 for line in vector_data:
322 line = line.strip()
323
324 # Blank lines and section headers are ignored
325 if not line or line.startswith("["):
326 continue
327
328 if line.startswith("# Salt len:"):
329 salt_length = int(line.split(":")[1].strip())
330 continue
331 elif line.startswith("#"):
332 continue
333
334 # Build our data using a simple Key = Value format
335 name, value = [c.strip() for c in line.split("=")]
336
337 if name == "n":
338 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400339 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400340 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400341 elif name == "p":
342 p = int(value, 16)
343 elif name == "q":
344 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400345 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400346 if p is None:
347 test_data = {
348 "modulus": n,
349 "public_exponent": e,
350 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400351 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400352 "fail": False
353 }
354 else:
355 test_data = {
356 "modulus": n,
357 "p": p,
358 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400359 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400360 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400361 if salt_length is not None:
362 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400363 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400364 elif name == "e" and p is not None:
365 test_data["public_exponent"] = int(value, 16)
366 elif name == "d":
367 test_data["private_exponent"] = int(value, 16)
368 elif name == "Result":
369 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400370 # For all other tokens we simply want the name, value stored in
371 # the dictionary
372 else:
373 test_data[name.lower()] = value.encode("ascii")
374
375 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200376
377
378def load_fips_dsa_key_pair_vectors(vector_data):
379 """
380 Loads data out of the FIPS DSA KeyPair vector files.
381 """
382 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200383 # When reading_key_data is set to True it tells the loader to continue
384 # constructing dictionaries. We set reading_key_data to False during the
385 # blocks of the vectors of N=224 because we don't support it.
386 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200387 for line in vector_data:
388 line = line.strip()
389
390 if not line or line.startswith("#"):
391 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200392 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200393 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200394 elif line.startswith("[mod = L=2048, N=224"):
395 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200396 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200397 elif line.startswith("[mod = L=2048, N=256"):
398 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200399 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200400 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200401 continue
Alex Gaynor0fe7db62015-06-27 17:20:59 -0400402
403 if reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200404 if line.startswith("P"):
405 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200406 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200407 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200408 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200409 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200410 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200411 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200412 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200413 vectors.append({'p': vectors[-1]['p'],
414 'q': vectors[-1]['q'],
415 'g': vectors[-1]['g'],
416 'x': int(line.split("=")[1], 16)
417 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200418 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200419 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200420
421 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100422
423
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200424def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200425 """
426 Loads data out of the FIPS DSA SigVer vector files.
427 """
428 vectors = []
429 sha_regex = re.compile(
430 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
431 )
432 # When reading_key_data is set to True it tells the loader to continue
433 # constructing dictionaries. We set reading_key_data to False during the
434 # blocks of the vectors of N=224 because we don't support it.
435 reading_key_data = True
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200436
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200437 for line in vector_data:
438 line = line.strip()
439
440 if not line or line.startswith("#"):
441 continue
442
443 sha_match = sha_regex.match(line)
444 if sha_match:
445 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
446
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500447 if line.startswith("[mod = L=2048, N=224"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200448 reading_key_data = False
449 continue
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500450 elif line.startswith("[mod = L=2048, N=256"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200451 reading_key_data = True
452 continue
453
454 if not reading_key_data or line.startswith("[mod"):
455 continue
456
457 name, value = [c.strip() for c in line.split("=")]
458
459 if name == "P":
460 vectors.append({'p': int(value, 16),
461 'digest_algorithm': digest_algorithm})
462 elif name == "Q":
463 vectors[-1]['q'] = int(value, 16)
464 elif name == "G":
465 vectors[-1]['g'] = int(value, 16)
466 elif name == "Msg" and 'msg' not in vectors[-1]:
467 hexmsg = value.strip().encode("ascii")
468 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
469 elif name == "Msg" and 'msg' in vectors[-1]:
470 hexmsg = value.strip().encode("ascii")
471 vectors.append({'p': vectors[-1]['p'],
472 'q': vectors[-1]['q'],
473 'g': vectors[-1]['g'],
474 'digest_algorithm':
475 vectors[-1]['digest_algorithm'],
476 'msg': binascii.unhexlify(hexmsg)})
477 elif name == "X":
478 vectors[-1]['x'] = int(value, 16)
479 elif name == "Y":
480 vectors[-1]['y'] = int(value, 16)
481 elif name == "R":
482 vectors[-1]['r'] = int(value, 16)
483 elif name == "S":
484 vectors[-1]['s'] = int(value, 16)
485 elif name == "Result":
486 vectors[-1]['result'] = value.split("(")[0].strip()
487
488 return vectors
489
490
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100491# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100492_ECDSA_CURVE_NAMES = {
493 "P-192": "secp192r1",
494 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100495 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100496 "P-384": "secp384r1",
497 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100498
Alex Stapletonc387cf72014-04-13 13:58:02 +0100499 "K-163": "sect163k1",
500 "K-233": "sect233k1",
Alex Stapletonf6a1cf62015-05-03 12:16:19 +0100501 "K-256": "secp256k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100502 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100503 "K-409": "sect409k1",
504 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100505
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100506 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100507 "B-233": "sect233r1",
508 "B-283": "sect283r1",
509 "B-409": "sect409r1",
510 "B-571": "sect571r1",
511}
512
513
Alex Stapletoncf048602014-04-12 12:48:59 +0100514def load_fips_ecdsa_key_pair_vectors(vector_data):
515 """
516 Loads data out of the FIPS ECDSA KeyPair vector files.
517 """
518 vectors = []
519 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100520 for line in vector_data:
521 line = line.strip()
522
523 if not line or line.startswith("#"):
524 continue
525
Alex Stapletonc387cf72014-04-13 13:58:02 +0100526 if line[1:-1] in _ECDSA_CURVE_NAMES:
527 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100528
529 elif line.startswith("d = "):
530 if key_data is not None:
531 vectors.append(key_data)
532
533 key_data = {
534 "curve": curve_name,
535 "d": int(line.split("=")[1], 16)
536 }
537
538 elif key_data is not None:
539 if line.startswith("Qx = "):
540 key_data["x"] = int(line.split("=")[1], 16)
541 elif line.startswith("Qy = "):
542 key_data["y"] = int(line.split("=")[1], 16)
543
544 if key_data is not None:
545 vectors.append(key_data)
546
547 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100548
549
550def load_fips_ecdsa_signing_vectors(vector_data):
551 """
552 Loads data out of the FIPS ECDSA SigGen vector files.
553 """
554 vectors = []
555
556 curve_rx = re.compile(
557 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
558 )
559
560 data = None
561 for line in vector_data:
562 line = line.strip()
563
564 if not line or line.startswith("#"):
565 continue
566
567 curve_match = curve_rx.match(line)
568 if curve_match:
569 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
570 digest_name = "SHA-{0}".format(curve_match.group("sha"))
571
572 elif line.startswith("Msg = "):
573 if data is not None:
574 vectors.append(data)
575
576 hexmsg = line.split("=")[1].strip().encode("ascii")
577
578 data = {
579 "curve": curve_name,
580 "digest_algorithm": digest_name,
581 "message": binascii.unhexlify(hexmsg)
582 }
583
584 elif data is not None:
585 if line.startswith("Qx = "):
586 data["x"] = int(line.split("=")[1], 16)
587 elif line.startswith("Qy = "):
588 data["y"] = int(line.split("=")[1], 16)
589 elif line.startswith("R = "):
590 data["r"] = int(line.split("=")[1], 16)
591 elif line.startswith("S = "):
592 data["s"] = int(line.split("=")[1], 16)
593 elif line.startswith("d = "):
594 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100595 elif line.startswith("Result = "):
596 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100597
598 if data is not None:
599 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100600 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100601
602
603def load_kasvs_dh_vectors(vector_data):
604 """
605 Loads data out of the KASVS key exchange vector data
606 """
607
608 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
609
610 vectors = []
611 data = {
612 "fail_z": False,
613 "fail_agree": False
614 }
615
616 for line in vector_data:
617 line = line.strip()
618
619 if not line or line.startswith("#"):
620 continue
621
622 if line.startswith("P = "):
623 data["p"] = int(line.split("=")[1], 16)
624 elif line.startswith("Q = "):
625 data["q"] = int(line.split("=")[1], 16)
626 elif line.startswith("G = "):
627 data["g"] = int(line.split("=")[1], 16)
628 elif line.startswith("Z = "):
629 z_hex = line.split("=")[1].strip().encode("ascii")
630 data["z"] = binascii.unhexlify(z_hex)
631 elif line.startswith("XstatCAVS = "):
632 data["x1"] = int(line.split("=")[1], 16)
633 elif line.startswith("YstatCAVS = "):
634 data["y1"] = int(line.split("=")[1], 16)
635 elif line.startswith("XstatIUT = "):
636 data["x2"] = int(line.split("=")[1], 16)
637 elif line.startswith("YstatIUT = "):
638 data["y2"] = int(line.split("=")[1], 16)
639 elif line.startswith("Result = "):
640 result_str = line.split("=")[1].strip()
641 match = result_rx.match(result_str)
642
643 if match.group(1) == "F":
644 if int(match.group(2)) in (5, 10):
645 data["fail_z"] = True
646 else:
647 data["fail_agree"] = True
648
649 vectors.append(data)
650
651 data = {
652 "p": data["p"],
653 "q": data["q"],
654 "g": data["g"],
655 "fail_z": False,
656 "fail_agree": False
657 }
658
659 return vectors
Simo Sorce917addb2015-04-29 19:41:26 -0400660
661
662def load_kasvs_ecdh_vectors(vector_data):
663 """
664 Loads data out of the KASVS key exchange vector data
665 """
666
667 curve_name_map = {
668 "P-192": "secp192r1",
669 "P-224": "secp224r1",
670 "P-256": "secp256r1",
671 "P-384": "secp384r1",
672 "P-521": "secp521r1",
673 }
674
675 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
676
677 tags = []
678 sets = dict()
679 vectors = []
680
681 # find info in header
682 for line in vector_data:
683 line = line.strip()
684
685 if line.startswith("#"):
686 parm = line.split("Parameter set(s) supported:")
687 if len(parm) == 2:
688 names = parm[1].strip().split()
689 for n in names:
690 tags.append("[%s]" % n)
691 break
692
693 # Sets Metadata
694 tag = None
695 curve = None
696 for line in vector_data:
697 line = line.strip()
698
699 if not line or line.startswith("#"):
700 continue
701
702 if line in tags:
703 tag = line
704 curve = None
705 elif line.startswith("[Curve selected:"):
706 curve = curve_name_map[line.split(':')[1].strip()[:-1]]
707
708 if tag is not None and curve is not None:
709 sets[tag.strip("[]")] = curve
710 tag = None
711 if len(tags) == len(sets):
712 break
713
714 # Data
715 data = {
716 "CAVS": dict(),
717 "IUT": dict(),
718 }
719 tag = None
720 for line in vector_data:
721 line = line.strip()
722
723 if not line or line.startswith("#"):
724 continue
725
726 if line.startswith("["):
727 tag = line.split()[0][1:]
728 elif line.startswith("COUNT = "):
729 data["COUNT"] = int(line.split("=")[1], 16)
730 elif line.startswith("dsCAVS = "):
731 data["CAVS"]["d"] = int(line.split("=")[1], 16)
732 elif line.startswith("QsCAVSx = "):
733 data["CAVS"]["x"] = int(line.split("=")[1], 16)
734 elif line.startswith("QsCAVSy = "):
735 data["CAVS"]["y"] = int(line.split("=")[1], 16)
736 elif line.startswith("dsIUT = "):
737 data["IUT"]["d"] = int(line.split("=")[1], 16)
738 elif line.startswith("QsIUTx = "):
739 data["IUT"]["x"] = int(line.split("=")[1], 16)
740 elif line.startswith("QsIUTy = "):
741 data["IUT"]["y"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400742 elif line.startswith("OI = "):
743 data["OI"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400744 elif line.startswith("Z = "):
745 data["Z"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400746 elif line.startswith("DKM = "):
747 data["DKM"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400748 elif line.startswith("Result = "):
749 result_str = line.split("=")[1].strip()
750 match = result_rx.match(result_str)
751
752 if match.group(1) == "F":
753 data["fail"] = True
754 else:
755 data["fail"] = False
756 data["errno"] = int(match.group(2))
757
758 data["curve"] = sets[tag]
759
760 vectors.append(data)
761
762 data = {
763 "CAVS": dict(),
764 "IUT": dict(),
765 }
766
767 return vectors