blob: 5083d48c39acdea955c92bce89391354e51afe72 [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 Gaynor50ebb482015-07-02 00:21:41 -040056 for mark in supported:
57 if not mark.kwargs["only_if"](item.funcargs["backend"]):
58 pytest.skip("{0} ({1})".format(
59 mark.kwargs["skip_message"], item.funcargs["backend"]
60 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060061 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060062 raise ValueError("This mark is only available on methods that take a "
63 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060064
65
Alex Gaynor7a489db2014-03-22 15:09:34 -070066@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000067def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070068 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000069 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000070
Alex Stapleton85a791f2014-03-27 16:55:41 +000071 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070072
73
Paul Kehrerfdae0702014-11-27 07:50:46 -100074def load_vectors_from_file(filename, loader, mode="r"):
75 with cryptography_vectors.open_vector_file(filename, mode) as vector_file:
Alex Stapletona39a3192014-03-14 20:03:12 +000076 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060077
78
Alex Gaynord3ce7032013-11-11 14:46:20 -080079def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060080 test_data = None
81 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040082
83 for line in vector_data:
84 line = line.strip()
85
Paul Kehrer749ac5b2013-11-18 18:12:41 -060086 # Blank lines, comments, and section headers are ignored
Alex Gaynore0a879f2015-02-15 20:54:34 -080087 if not line or line.startswith("#") or (line.startswith("[") and
88 line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080089 continue
90
Paul Kehrera43b6692013-11-12 15:35:49 -060091 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060092 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060093 continue
94
Donald Stufft9e1a48b2013-08-09 00:32:30 -040095 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060096 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040097
Paul Kehrer1050ddf2014-01-27 21:04:03 -060098 # Some tests (PBKDF2) contain \0, which should be interpreted as a
99 # null character rather than literal.
100 value = value.replace("\\0", "\0")
101
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400102 # COUNT is a special token that indicates a new block of data
103 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600104 test_data = {}
105 data.append(test_data)
106 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400107 # For all other tokens we simply want the name, value stored in
108 # the dictionary
109 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600110 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400111
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600112 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400113
114
Paul Kehrer1951bf62013-09-15 12:05:43 -0500115def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500116 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500117
118 for line in vector_data:
119 line = line.strip()
120
121 # Blank lines and comments are ignored
122 if not line or line.startswith("#"):
123 continue
124
125 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500126 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500127 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500128 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500129 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500130 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
131 # after a C is found the K+P+C tuple is complete
132 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700133 cryptrec_list.append({
134 "key": key,
135 "plaintext": pt,
136 "ciphertext": ct
137 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400138 else:
139 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500140 return cryptrec_list
141
142
Paul Kehrer69e06522013-10-18 17:28:39 -0500143def load_hash_vectors(vector_data):
144 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500145 key = None
146 msg = None
147 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500148
149 for line in vector_data:
150 line = line.strip()
151
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500152 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500153 continue
154
155 if line.startswith("Len"):
156 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500157 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800158 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500159 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500160 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800161 # In the NIST vectors they have chosen to represent an empty
162 # string as hex 00, which is of course not actually an empty
163 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500164 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
165 elif line.startswith("MD"):
166 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500167 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500168 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800169 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500170 key = None
171 msg = None
172 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500173 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800174 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500175 msg = None
176 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500177 else:
178 raise ValueError("Unknown line in hash vector")
179 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000180
181
182def load_pkcs1_vectors(vector_data):
183 """
184 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000185 """
186 private_key_vector = None
187 public_key_vector = None
188 attr = None
189 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600190 example_vector = None
191 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000192 vectors = []
193 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600194 if (
195 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500196 line.startswith("# OAEP Example") or
197 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600198 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600199 if example_vector:
200 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600201 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600202 example_vector[key] = hex_str
203 examples.append(example_vector)
204
205 attr = None
206 example_vector = collections.defaultdict(list)
207
Paul Kehrer3fe91502014-03-29 12:08:39 -0500208 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600209 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600210 continue
211 elif line.startswith("# Salt"):
212 attr = "salt"
213 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500214 elif line.startswith("# Seed"):
215 attr = "seed"
216 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600217 elif line.startswith("# Signature"):
218 attr = "signature"
219 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500220 elif line.startswith("# Encryption"):
221 attr = "encryption"
222 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600223 elif (
224 example_vector and
225 line.startswith("# =============================================")
226 ):
227 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600228 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600229 example_vector[key] = hex_str
230 examples.append(example_vector)
231 example_vector = None
232 attr = None
233 elif example_vector and line.startswith("#"):
234 continue
235 else:
236 if attr is not None and example_vector is not None:
237 example_vector[attr].append(line.strip())
238 continue
239
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000240 if (
241 line.startswith("# Example") or
242 line.startswith("# =============================================")
243 ):
244 if key:
245 assert private_key_vector
246 assert public_key_vector
247
248 for key, value in six.iteritems(public_key_vector):
249 hex_str = "".join(value).replace(" ", "")
250 public_key_vector[key] = int(hex_str, 16)
251
252 for key, value in six.iteritems(private_key_vector):
253 hex_str = "".join(value).replace(" ", "")
254 private_key_vector[key] = int(hex_str, 16)
255
Paul Kehrerefca2802014-02-17 20:55:13 -0600256 private_key_vector["examples"] = examples
257 examples = []
258
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000259 assert (
260 private_key_vector['public_exponent'] ==
261 public_key_vector['public_exponent']
262 )
263
264 assert (
265 private_key_vector['modulus'] ==
266 public_key_vector['modulus']
267 )
268
269 vectors.append(
270 (private_key_vector, public_key_vector)
271 )
272
273 public_key_vector = collections.defaultdict(list)
274 private_key_vector = collections.defaultdict(list)
275 key = None
276 attr = None
277
278 if private_key_vector is None or public_key_vector is None:
279 continue
280
281 if line.startswith("# Private key"):
282 key = private_key_vector
283 elif line.startswith("# Public key"):
284 key = public_key_vector
285 elif line.startswith("# Modulus:"):
286 attr = "modulus"
287 elif line.startswith("# Public exponent:"):
288 attr = "public_exponent"
289 elif line.startswith("# Exponent:"):
290 if key is public_key_vector:
291 attr = "public_exponent"
292 else:
293 assert key is private_key_vector
294 attr = "private_exponent"
295 elif line.startswith("# Prime 1:"):
296 attr = "p"
297 elif line.startswith("# Prime 2:"):
298 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600299 elif line.startswith("# Prime exponent 1:"):
300 attr = "dmp1"
301 elif line.startswith("# Prime exponent 2:"):
302 attr = "dmq1"
303 elif line.startswith("# Coefficient:"):
304 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000305 elif line.startswith("#"):
306 attr = None
307 else:
308 if key is not None and attr is not None:
309 key[attr].append(line.strip())
310 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400311
312
313def load_rsa_nist_vectors(vector_data):
314 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400315 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400316 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400317 data = []
318
319 for line in vector_data:
320 line = line.strip()
321
322 # Blank lines and section headers are ignored
323 if not line or line.startswith("["):
324 continue
325
326 if line.startswith("# Salt len:"):
327 salt_length = int(line.split(":")[1].strip())
328 continue
329 elif line.startswith("#"):
330 continue
331
332 # Build our data using a simple Key = Value format
333 name, value = [c.strip() for c in line.split("=")]
334
335 if name == "n":
336 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400337 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400338 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400339 elif name == "p":
340 p = int(value, 16)
341 elif name == "q":
342 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400343 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400344 if p is None:
345 test_data = {
346 "modulus": n,
347 "public_exponent": e,
348 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400349 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400350 "fail": False
351 }
352 else:
353 test_data = {
354 "modulus": n,
355 "p": p,
356 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400357 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400358 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400359 if salt_length is not None:
360 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400361 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400362 elif name == "e" and p is not None:
363 test_data["public_exponent"] = int(value, 16)
364 elif name == "d":
365 test_data["private_exponent"] = int(value, 16)
366 elif name == "Result":
367 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400368 # For all other tokens we simply want the name, value stored in
369 # the dictionary
370 else:
371 test_data[name.lower()] = value.encode("ascii")
372
373 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200374
375
376def load_fips_dsa_key_pair_vectors(vector_data):
377 """
378 Loads data out of the FIPS DSA KeyPair vector files.
379 """
380 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200381 # When reading_key_data is set to True it tells the loader to continue
382 # constructing dictionaries. We set reading_key_data to False during the
383 # blocks of the vectors of N=224 because we don't support it.
384 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200385 for line in vector_data:
386 line = line.strip()
387
388 if not line or line.startswith("#"):
389 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200390 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200391 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200392 elif line.startswith("[mod = L=2048, N=224"):
393 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200394 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200395 elif line.startswith("[mod = L=2048, N=256"):
396 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200397 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200398 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200399 continue
Alex Gaynor0fe7db62015-06-27 17:20:59 -0400400
401 if reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200402 if line.startswith("P"):
403 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200404 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200405 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200406 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200407 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200408 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200409 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200410 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200411 vectors.append({'p': vectors[-1]['p'],
412 'q': vectors[-1]['q'],
413 'g': vectors[-1]['g'],
414 'x': int(line.split("=")[1], 16)
415 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200416 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200417 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200418
419 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100420
421
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200422def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200423 """
424 Loads data out of the FIPS DSA SigVer vector files.
425 """
426 vectors = []
427 sha_regex = re.compile(
428 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
429 )
430 # When reading_key_data is set to True it tells the loader to continue
431 # constructing dictionaries. We set reading_key_data to False during the
432 # blocks of the vectors of N=224 because we don't support it.
433 reading_key_data = True
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200434
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200435 for line in vector_data:
436 line = line.strip()
437
438 if not line or line.startswith("#"):
439 continue
440
441 sha_match = sha_regex.match(line)
442 if sha_match:
443 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
444
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500445 if line.startswith("[mod = L=2048, N=224"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200446 reading_key_data = False
447 continue
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500448 elif line.startswith("[mod = L=2048, N=256"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200449 reading_key_data = True
450 continue
451
452 if not reading_key_data or line.startswith("[mod"):
453 continue
454
455 name, value = [c.strip() for c in line.split("=")]
456
457 if name == "P":
458 vectors.append({'p': int(value, 16),
459 'digest_algorithm': digest_algorithm})
460 elif name == "Q":
461 vectors[-1]['q'] = int(value, 16)
462 elif name == "G":
463 vectors[-1]['g'] = int(value, 16)
464 elif name == "Msg" and 'msg' not in vectors[-1]:
465 hexmsg = value.strip().encode("ascii")
466 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
467 elif name == "Msg" and 'msg' in vectors[-1]:
468 hexmsg = value.strip().encode("ascii")
469 vectors.append({'p': vectors[-1]['p'],
470 'q': vectors[-1]['q'],
471 'g': vectors[-1]['g'],
472 'digest_algorithm':
473 vectors[-1]['digest_algorithm'],
474 'msg': binascii.unhexlify(hexmsg)})
475 elif name == "X":
476 vectors[-1]['x'] = int(value, 16)
477 elif name == "Y":
478 vectors[-1]['y'] = int(value, 16)
479 elif name == "R":
480 vectors[-1]['r'] = int(value, 16)
481 elif name == "S":
482 vectors[-1]['s'] = int(value, 16)
483 elif name == "Result":
484 vectors[-1]['result'] = value.split("(")[0].strip()
485
486 return vectors
487
488
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100489# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100490_ECDSA_CURVE_NAMES = {
491 "P-192": "secp192r1",
492 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100493 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100494 "P-384": "secp384r1",
495 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100496
Alex Stapletonc387cf72014-04-13 13:58:02 +0100497 "K-163": "sect163k1",
498 "K-233": "sect233k1",
Alex Stapletonf6a1cf62015-05-03 12:16:19 +0100499 "K-256": "secp256k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100500 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100501 "K-409": "sect409k1",
502 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100503
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100504 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100505 "B-233": "sect233r1",
506 "B-283": "sect283r1",
507 "B-409": "sect409r1",
508 "B-571": "sect571r1",
509}
510
511
Alex Stapletoncf048602014-04-12 12:48:59 +0100512def load_fips_ecdsa_key_pair_vectors(vector_data):
513 """
514 Loads data out of the FIPS ECDSA KeyPair vector files.
515 """
516 vectors = []
517 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100518 for line in vector_data:
519 line = line.strip()
520
521 if not line or line.startswith("#"):
522 continue
523
Alex Stapletonc387cf72014-04-13 13:58:02 +0100524 if line[1:-1] in _ECDSA_CURVE_NAMES:
525 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100526
527 elif line.startswith("d = "):
528 if key_data is not None:
529 vectors.append(key_data)
530
531 key_data = {
532 "curve": curve_name,
533 "d": int(line.split("=")[1], 16)
534 }
535
536 elif key_data is not None:
537 if line.startswith("Qx = "):
538 key_data["x"] = int(line.split("=")[1], 16)
539 elif line.startswith("Qy = "):
540 key_data["y"] = int(line.split("=")[1], 16)
541
542 if key_data is not None:
543 vectors.append(key_data)
544
545 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100546
547
548def load_fips_ecdsa_signing_vectors(vector_data):
549 """
550 Loads data out of the FIPS ECDSA SigGen vector files.
551 """
552 vectors = []
553
554 curve_rx = re.compile(
555 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
556 )
557
558 data = None
559 for line in vector_data:
560 line = line.strip()
561
562 if not line or line.startswith("#"):
563 continue
564
565 curve_match = curve_rx.match(line)
566 if curve_match:
567 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
568 digest_name = "SHA-{0}".format(curve_match.group("sha"))
569
570 elif line.startswith("Msg = "):
571 if data is not None:
572 vectors.append(data)
573
574 hexmsg = line.split("=")[1].strip().encode("ascii")
575
576 data = {
577 "curve": curve_name,
578 "digest_algorithm": digest_name,
579 "message": binascii.unhexlify(hexmsg)
580 }
581
582 elif data is not None:
583 if line.startswith("Qx = "):
584 data["x"] = int(line.split("=")[1], 16)
585 elif line.startswith("Qy = "):
586 data["y"] = int(line.split("=")[1], 16)
587 elif line.startswith("R = "):
588 data["r"] = int(line.split("=")[1], 16)
589 elif line.startswith("S = "):
590 data["s"] = int(line.split("=")[1], 16)
591 elif line.startswith("d = "):
592 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100593 elif line.startswith("Result = "):
594 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100595
596 if data is not None:
597 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100598 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100599
600
601def load_kasvs_dh_vectors(vector_data):
602 """
603 Loads data out of the KASVS key exchange vector data
604 """
605
606 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
607
608 vectors = []
609 data = {
610 "fail_z": False,
611 "fail_agree": False
612 }
613
614 for line in vector_data:
615 line = line.strip()
616
617 if not line or line.startswith("#"):
618 continue
619
620 if line.startswith("P = "):
621 data["p"] = int(line.split("=")[1], 16)
622 elif line.startswith("Q = "):
623 data["q"] = int(line.split("=")[1], 16)
624 elif line.startswith("G = "):
625 data["g"] = int(line.split("=")[1], 16)
626 elif line.startswith("Z = "):
627 z_hex = line.split("=")[1].strip().encode("ascii")
628 data["z"] = binascii.unhexlify(z_hex)
629 elif line.startswith("XstatCAVS = "):
630 data["x1"] = int(line.split("=")[1], 16)
631 elif line.startswith("YstatCAVS = "):
632 data["y1"] = int(line.split("=")[1], 16)
633 elif line.startswith("XstatIUT = "):
634 data["x2"] = int(line.split("=")[1], 16)
635 elif line.startswith("YstatIUT = "):
636 data["y2"] = int(line.split("=")[1], 16)
637 elif line.startswith("Result = "):
638 result_str = line.split("=")[1].strip()
639 match = result_rx.match(result_str)
640
641 if match.group(1) == "F":
642 if int(match.group(2)) in (5, 10):
643 data["fail_z"] = True
644 else:
645 data["fail_agree"] = True
646
647 vectors.append(data)
648
649 data = {
650 "p": data["p"],
651 "q": data["q"],
652 "g": data["g"],
653 "fail_z": False,
654 "fail_agree": False
655 }
656
657 return vectors
Simo Sorce917addb2015-04-29 19:41:26 -0400658
659
660def load_kasvs_ecdh_vectors(vector_data):
661 """
662 Loads data out of the KASVS key exchange vector data
663 """
664
665 curve_name_map = {
666 "P-192": "secp192r1",
667 "P-224": "secp224r1",
668 "P-256": "secp256r1",
669 "P-384": "secp384r1",
670 "P-521": "secp521r1",
671 }
672
673 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
674
675 tags = []
676 sets = dict()
677 vectors = []
678
679 # find info in header
680 for line in vector_data:
681 line = line.strip()
682
683 if line.startswith("#"):
684 parm = line.split("Parameter set(s) supported:")
685 if len(parm) == 2:
686 names = parm[1].strip().split()
687 for n in names:
688 tags.append("[%s]" % n)
689 break
690
691 # Sets Metadata
692 tag = None
693 curve = None
694 for line in vector_data:
695 line = line.strip()
696
697 if not line or line.startswith("#"):
698 continue
699
700 if line in tags:
701 tag = line
702 curve = None
703 elif line.startswith("[Curve selected:"):
704 curve = curve_name_map[line.split(':')[1].strip()[:-1]]
705
706 if tag is not None and curve is not None:
707 sets[tag.strip("[]")] = curve
708 tag = None
709 if len(tags) == len(sets):
710 break
711
712 # Data
713 data = {
714 "CAVS": dict(),
715 "IUT": dict(),
716 }
717 tag = None
718 for line in vector_data:
719 line = line.strip()
720
721 if not line or line.startswith("#"):
722 continue
723
724 if line.startswith("["):
725 tag = line.split()[0][1:]
726 elif line.startswith("COUNT = "):
727 data["COUNT"] = int(line.split("=")[1], 16)
728 elif line.startswith("dsCAVS = "):
729 data["CAVS"]["d"] = int(line.split("=")[1], 16)
730 elif line.startswith("QsCAVSx = "):
731 data["CAVS"]["x"] = int(line.split("=")[1], 16)
732 elif line.startswith("QsCAVSy = "):
733 data["CAVS"]["y"] = int(line.split("=")[1], 16)
734 elif line.startswith("dsIUT = "):
735 data["IUT"]["d"] = int(line.split("=")[1], 16)
736 elif line.startswith("QsIUTx = "):
737 data["IUT"]["x"] = int(line.split("=")[1], 16)
738 elif line.startswith("QsIUTy = "):
739 data["IUT"]["y"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400740 elif line.startswith("OI = "):
741 data["OI"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400742 elif line.startswith("Z = "):
743 data["Z"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400744 elif line.startswith("DKM = "):
745 data["DKM"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400746 elif line.startswith("Result = "):
747 result_str = line.split("=")[1].strip()
748 match = result_rx.match(result_str)
749
750 if match.group(1) == "F":
751 data["fail"] = True
752 else:
753 data["fail"] = False
754 data["errno"] = int(match.group(2))
755
756 data["curve"] = sets[tag]
757
758 vectors.append(data)
759
760 data = {
761 "CAVS": dict(),
762 "IUT": dict(),
763 }
764
765 return vectors