blob: cc3f9fcc2346fbed33574c42c24fc056199e0e82 [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
Paul Kehrerc421e632014-01-18 09:22:21 -060028def select_backends(names, backend_list):
29 if names is None:
30 return backend_list
31 split_names = [x.strip() for x in names.split(',')]
Paul Kehreraed9e172014-01-19 12:09:27 -060032 selected_backends = []
33 for backend in backend_list:
34 if backend.name in split_names:
35 selected_backends.append(backend)
Paul Kehrerc421e632014-01-18 09:22:21 -060036
Paul Kehreraed9e172014-01-19 12:09:27 -060037 if len(selected_backends) > 0:
38 return selected_backends
Paul Kehrerc421e632014-01-18 09:22:21 -060039 else:
40 raise ValueError(
41 "No backend selected. Tried to select: {0}".format(split_names)
42 )
Paul Kehrer34c075e2014-01-13 21:52:08 -050043
44
Paul Kehrer902d8cf2014-10-25 12:22:10 -070045def skip_if_empty(backend_list, required_interfaces):
46 if not backend_list:
47 pytest.skip(
48 "No backends provided supply the interface: {0}".format(
49 ", ".join(iface.__name__ for iface in required_interfaces)
50 )
51 )
52
53
Paul Kehrer60fc8da2013-12-26 20:19:34 -060054def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060055 supported = item.keywords.get("supported")
56 if supported and "backend" in item.funcargs:
Alex Gaynor50ebb482015-07-02 00:21:41 -040057 for mark in supported:
58 if not mark.kwargs["only_if"](item.funcargs["backend"]):
59 pytest.skip("{0} ({1})".format(
60 mark.kwargs["skip_message"], item.funcargs["backend"]
61 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060062 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060063 raise ValueError("This mark is only available on methods that take a "
64 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060065
66
Alex Gaynor7a489db2014-03-22 15:09:34 -070067@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000068def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070069 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000070 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000071
Alex Stapleton85a791f2014-03-27 16:55:41 +000072 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070073
74
Paul Kehrerfdae0702014-11-27 07:50:46 -100075def load_vectors_from_file(filename, loader, mode="r"):
76 with cryptography_vectors.open_vector_file(filename, mode) as vector_file:
Alex Stapletona39a3192014-03-14 20:03:12 +000077 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060078
79
Alex Gaynord3ce7032013-11-11 14:46:20 -080080def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060081 test_data = None
82 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040083
84 for line in vector_data:
85 line = line.strip()
86
Paul Kehrer749ac5b2013-11-18 18:12:41 -060087 # Blank lines, comments, and section headers are ignored
Alex Gaynore0a879f2015-02-15 20:54:34 -080088 if not line or line.startswith("#") or (line.startswith("[") and
89 line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080090 continue
91
Paul Kehrera43b6692013-11-12 15:35:49 -060092 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060093 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060094 continue
95
Donald Stufft9e1a48b2013-08-09 00:32:30 -040096 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060097 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040098
Paul Kehrer1050ddf2014-01-27 21:04:03 -060099 # Some tests (PBKDF2) contain \0, which should be interpreted as a
100 # null character rather than literal.
101 value = value.replace("\\0", "\0")
102
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400103 # COUNT is a special token that indicates a new block of data
104 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600105 test_data = {}
106 data.append(test_data)
107 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400108 # For all other tokens we simply want the name, value stored in
109 # the dictionary
110 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600111 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400112
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600113 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400114
115
Paul Kehrer1951bf62013-09-15 12:05:43 -0500116def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500117 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500118
119 for line in vector_data:
120 line = line.strip()
121
122 # Blank lines and comments are ignored
123 if not line or line.startswith("#"):
124 continue
125
126 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500127 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500128 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500129 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500130 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500131 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
132 # after a C is found the K+P+C tuple is complete
133 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700134 cryptrec_list.append({
135 "key": key,
136 "plaintext": pt,
137 "ciphertext": ct
138 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400139 else:
140 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500141 return cryptrec_list
142
143
Paul Kehrer69e06522013-10-18 17:28:39 -0500144def load_hash_vectors(vector_data):
145 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500146 key = None
147 msg = None
148 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500149
150 for line in vector_data:
151 line = line.strip()
152
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500153 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500154 continue
155
156 if line.startswith("Len"):
157 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500158 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800159 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500160 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500161 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800162 # In the NIST vectors they have chosen to represent an empty
163 # string as hex 00, which is of course not actually an empty
164 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500165 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
166 elif line.startswith("MD"):
167 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500168 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500169 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800170 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500171 key = None
172 msg = None
173 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500174 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800175 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500176 msg = None
177 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500178 else:
179 raise ValueError("Unknown line in hash vector")
180 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000181
182
183def load_pkcs1_vectors(vector_data):
184 """
185 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000186 """
187 private_key_vector = None
188 public_key_vector = None
189 attr = None
190 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600191 example_vector = None
192 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000193 vectors = []
194 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600195 if (
196 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500197 line.startswith("# OAEP Example") or
198 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600199 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600200 if example_vector:
201 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600202 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600203 example_vector[key] = hex_str
204 examples.append(example_vector)
205
206 attr = None
207 example_vector = collections.defaultdict(list)
208
Paul Kehrer3fe91502014-03-29 12:08:39 -0500209 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600210 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600211 continue
212 elif line.startswith("# Salt"):
213 attr = "salt"
214 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500215 elif line.startswith("# Seed"):
216 attr = "seed"
217 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600218 elif line.startswith("# Signature"):
219 attr = "signature"
220 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500221 elif line.startswith("# Encryption"):
222 attr = "encryption"
223 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600224 elif (
225 example_vector and
226 line.startswith("# =============================================")
227 ):
228 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600229 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600230 example_vector[key] = hex_str
231 examples.append(example_vector)
232 example_vector = None
233 attr = None
234 elif example_vector and line.startswith("#"):
235 continue
236 else:
237 if attr is not None and example_vector is not None:
238 example_vector[attr].append(line.strip())
239 continue
240
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000241 if (
242 line.startswith("# Example") or
243 line.startswith("# =============================================")
244 ):
245 if key:
246 assert private_key_vector
247 assert public_key_vector
248
249 for key, value in six.iteritems(public_key_vector):
250 hex_str = "".join(value).replace(" ", "")
251 public_key_vector[key] = int(hex_str, 16)
252
253 for key, value in six.iteritems(private_key_vector):
254 hex_str = "".join(value).replace(" ", "")
255 private_key_vector[key] = int(hex_str, 16)
256
Paul Kehrerefca2802014-02-17 20:55:13 -0600257 private_key_vector["examples"] = examples
258 examples = []
259
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000260 assert (
261 private_key_vector['public_exponent'] ==
262 public_key_vector['public_exponent']
263 )
264
265 assert (
266 private_key_vector['modulus'] ==
267 public_key_vector['modulus']
268 )
269
270 vectors.append(
271 (private_key_vector, public_key_vector)
272 )
273
274 public_key_vector = collections.defaultdict(list)
275 private_key_vector = collections.defaultdict(list)
276 key = None
277 attr = None
278
279 if private_key_vector is None or public_key_vector is None:
280 continue
281
282 if line.startswith("# Private key"):
283 key = private_key_vector
284 elif line.startswith("# Public key"):
285 key = public_key_vector
286 elif line.startswith("# Modulus:"):
287 attr = "modulus"
288 elif line.startswith("# Public exponent:"):
289 attr = "public_exponent"
290 elif line.startswith("# Exponent:"):
291 if key is public_key_vector:
292 attr = "public_exponent"
293 else:
294 assert key is private_key_vector
295 attr = "private_exponent"
296 elif line.startswith("# Prime 1:"):
297 attr = "p"
298 elif line.startswith("# Prime 2:"):
299 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600300 elif line.startswith("# Prime exponent 1:"):
301 attr = "dmp1"
302 elif line.startswith("# Prime exponent 2:"):
303 attr = "dmq1"
304 elif line.startswith("# Coefficient:"):
305 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000306 elif line.startswith("#"):
307 attr = None
308 else:
309 if key is not None and attr is not None:
310 key[attr].append(line.strip())
311 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400312
313
314def load_rsa_nist_vectors(vector_data):
315 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400316 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400317 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400318 data = []
319
320 for line in vector_data:
321 line = line.strip()
322
323 # Blank lines and section headers are ignored
324 if not line or line.startswith("["):
325 continue
326
327 if line.startswith("# Salt len:"):
328 salt_length = int(line.split(":")[1].strip())
329 continue
330 elif line.startswith("#"):
331 continue
332
333 # Build our data using a simple Key = Value format
334 name, value = [c.strip() for c in line.split("=")]
335
336 if name == "n":
337 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400338 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400339 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400340 elif name == "p":
341 p = int(value, 16)
342 elif name == "q":
343 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400344 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400345 if p is None:
346 test_data = {
347 "modulus": n,
348 "public_exponent": e,
349 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400350 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400351 "fail": False
352 }
353 else:
354 test_data = {
355 "modulus": n,
356 "p": p,
357 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400358 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400359 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400360 if salt_length is not None:
361 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400362 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400363 elif name == "e" and p is not None:
364 test_data["public_exponent"] = int(value, 16)
365 elif name == "d":
366 test_data["private_exponent"] = int(value, 16)
367 elif name == "Result":
368 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400369 # For all other tokens we simply want the name, value stored in
370 # the dictionary
371 else:
372 test_data[name.lower()] = value.encode("ascii")
373
374 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200375
376
377def load_fips_dsa_key_pair_vectors(vector_data):
378 """
379 Loads data out of the FIPS DSA KeyPair vector files.
380 """
381 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200382 # When reading_key_data is set to True it tells the loader to continue
383 # constructing dictionaries. We set reading_key_data to False during the
384 # blocks of the vectors of N=224 because we don't support it.
385 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200386 for line in vector_data:
387 line = line.strip()
388
389 if not line or line.startswith("#"):
390 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200391 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200392 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200393 elif line.startswith("[mod = L=2048, N=224"):
394 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200395 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200396 elif line.startswith("[mod = L=2048, N=256"):
397 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200398 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200399 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200400 continue
Alex Gaynor0fe7db62015-06-27 17:20:59 -0400401
402 if reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200403 if line.startswith("P"):
404 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200405 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200406 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200407 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200408 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200409 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200410 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200411 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200412 vectors.append({'p': vectors[-1]['p'],
413 'q': vectors[-1]['q'],
414 'g': vectors[-1]['g'],
415 'x': int(line.split("=")[1], 16)
416 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200417 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200418 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200419
420 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100421
422
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200423def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200424 """
425 Loads data out of the FIPS DSA SigVer vector files.
426 """
427 vectors = []
428 sha_regex = re.compile(
429 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
430 )
431 # When reading_key_data is set to True it tells the loader to continue
432 # constructing dictionaries. We set reading_key_data to False during the
433 # blocks of the vectors of N=224 because we don't support it.
434 reading_key_data = True
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200435
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200436 for line in vector_data:
437 line = line.strip()
438
439 if not line or line.startswith("#"):
440 continue
441
442 sha_match = sha_regex.match(line)
443 if sha_match:
444 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
445
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500446 if line.startswith("[mod = L=2048, N=224"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200447 reading_key_data = False
448 continue
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500449 elif line.startswith("[mod = L=2048, N=256"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200450 reading_key_data = True
451 continue
452
453 if not reading_key_data or line.startswith("[mod"):
454 continue
455
456 name, value = [c.strip() for c in line.split("=")]
457
458 if name == "P":
459 vectors.append({'p': int(value, 16),
460 'digest_algorithm': digest_algorithm})
461 elif name == "Q":
462 vectors[-1]['q'] = int(value, 16)
463 elif name == "G":
464 vectors[-1]['g'] = int(value, 16)
465 elif name == "Msg" and 'msg' not in vectors[-1]:
466 hexmsg = value.strip().encode("ascii")
467 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
468 elif name == "Msg" and 'msg' in vectors[-1]:
469 hexmsg = value.strip().encode("ascii")
470 vectors.append({'p': vectors[-1]['p'],
471 'q': vectors[-1]['q'],
472 'g': vectors[-1]['g'],
473 'digest_algorithm':
474 vectors[-1]['digest_algorithm'],
475 'msg': binascii.unhexlify(hexmsg)})
476 elif name == "X":
477 vectors[-1]['x'] = int(value, 16)
478 elif name == "Y":
479 vectors[-1]['y'] = int(value, 16)
480 elif name == "R":
481 vectors[-1]['r'] = int(value, 16)
482 elif name == "S":
483 vectors[-1]['s'] = int(value, 16)
484 elif name == "Result":
485 vectors[-1]['result'] = value.split("(")[0].strip()
486
487 return vectors
488
489
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100490# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100491_ECDSA_CURVE_NAMES = {
492 "P-192": "secp192r1",
493 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100494 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100495 "P-384": "secp384r1",
496 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100497
Alex Stapletonc387cf72014-04-13 13:58:02 +0100498 "K-163": "sect163k1",
499 "K-233": "sect233k1",
Alex Stapletonf6a1cf62015-05-03 12:16:19 +0100500 "K-256": "secp256k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100501 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100502 "K-409": "sect409k1",
503 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100504
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100505 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100506 "B-233": "sect233r1",
507 "B-283": "sect283r1",
508 "B-409": "sect409r1",
509 "B-571": "sect571r1",
510}
511
512
Alex Stapletoncf048602014-04-12 12:48:59 +0100513def load_fips_ecdsa_key_pair_vectors(vector_data):
514 """
515 Loads data out of the FIPS ECDSA KeyPair vector files.
516 """
517 vectors = []
518 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100519 for line in vector_data:
520 line = line.strip()
521
522 if not line or line.startswith("#"):
523 continue
524
Alex Stapletonc387cf72014-04-13 13:58:02 +0100525 if line[1:-1] in _ECDSA_CURVE_NAMES:
526 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100527
528 elif line.startswith("d = "):
529 if key_data is not None:
530 vectors.append(key_data)
531
532 key_data = {
533 "curve": curve_name,
534 "d": int(line.split("=")[1], 16)
535 }
536
537 elif key_data is not None:
538 if line.startswith("Qx = "):
539 key_data["x"] = int(line.split("=")[1], 16)
540 elif line.startswith("Qy = "):
541 key_data["y"] = int(line.split("=")[1], 16)
542
Paul Kehrerb60b8dd2015-08-01 19:47:22 +0100543 assert key_data is not None
544 vectors.append(key_data)
Alex Stapletoncf048602014-04-12 12:48:59 +0100545
546 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100547
548
549def load_fips_ecdsa_signing_vectors(vector_data):
550 """
551 Loads data out of the FIPS ECDSA SigGen vector files.
552 """
553 vectors = []
554
555 curve_rx = re.compile(
556 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
557 )
558
559 data = None
560 for line in vector_data:
561 line = line.strip()
562
Alex Stapletonc387cf72014-04-13 13:58:02 +0100563 curve_match = curve_rx.match(line)
564 if curve_match:
565 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
566 digest_name = "SHA-{0}".format(curve_match.group("sha"))
567
568 elif line.startswith("Msg = "):
569 if data is not None:
570 vectors.append(data)
571
572 hexmsg = line.split("=")[1].strip().encode("ascii")
573
574 data = {
575 "curve": curve_name,
576 "digest_algorithm": digest_name,
577 "message": binascii.unhexlify(hexmsg)
578 }
579
580 elif data is not None:
581 if line.startswith("Qx = "):
582 data["x"] = int(line.split("=")[1], 16)
583 elif line.startswith("Qy = "):
584 data["y"] = int(line.split("=")[1], 16)
585 elif line.startswith("R = "):
586 data["r"] = int(line.split("=")[1], 16)
587 elif line.startswith("S = "):
588 data["s"] = int(line.split("=")[1], 16)
589 elif line.startswith("d = "):
590 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100591 elif line.startswith("Result = "):
592 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100593
Paul Kehrerb60b8dd2015-08-01 19:47:22 +0100594 assert data is not None
595 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100596 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100597
598
599def load_kasvs_dh_vectors(vector_data):
600 """
601 Loads data out of the KASVS key exchange vector data
602 """
603
604 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
605
606 vectors = []
607 data = {
608 "fail_z": False,
609 "fail_agree": False
610 }
611
612 for line in vector_data:
613 line = line.strip()
614
615 if not line or line.startswith("#"):
616 continue
617
618 if line.startswith("P = "):
619 data["p"] = int(line.split("=")[1], 16)
620 elif line.startswith("Q = "):
621 data["q"] = int(line.split("=")[1], 16)
622 elif line.startswith("G = "):
623 data["g"] = int(line.split("=")[1], 16)
624 elif line.startswith("Z = "):
625 z_hex = line.split("=")[1].strip().encode("ascii")
626 data["z"] = binascii.unhexlify(z_hex)
627 elif line.startswith("XstatCAVS = "):
628 data["x1"] = int(line.split("=")[1], 16)
629 elif line.startswith("YstatCAVS = "):
630 data["y1"] = int(line.split("=")[1], 16)
631 elif line.startswith("XstatIUT = "):
632 data["x2"] = int(line.split("=")[1], 16)
633 elif line.startswith("YstatIUT = "):
634 data["y2"] = int(line.split("=")[1], 16)
635 elif line.startswith("Result = "):
636 result_str = line.split("=")[1].strip()
637 match = result_rx.match(result_str)
638
639 if match.group(1) == "F":
640 if int(match.group(2)) in (5, 10):
641 data["fail_z"] = True
642 else:
643 data["fail_agree"] = True
644
645 vectors.append(data)
646
647 data = {
648 "p": data["p"],
649 "q": data["q"],
650 "g": data["g"],
651 "fail_z": False,
652 "fail_agree": False
653 }
654
655 return vectors
Simo Sorce917addb2015-04-29 19:41:26 -0400656
657
658def load_kasvs_ecdh_vectors(vector_data):
659 """
660 Loads data out of the KASVS key exchange vector data
661 """
662
663 curve_name_map = {
664 "P-192": "secp192r1",
665 "P-224": "secp224r1",
666 "P-256": "secp256r1",
667 "P-384": "secp384r1",
668 "P-521": "secp521r1",
669 }
670
671 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
672
673 tags = []
Alex Gaynorace036d2015-09-24 20:23:08 -0400674 sets = {}
Simo Sorce917addb2015-04-29 19:41:26 -0400675 vectors = []
676
677 # find info in header
678 for line in vector_data:
679 line = line.strip()
680
681 if line.startswith("#"):
682 parm = line.split("Parameter set(s) supported:")
683 if len(parm) == 2:
684 names = parm[1].strip().split()
685 for n in names:
686 tags.append("[%s]" % n)
687 break
688
689 # Sets Metadata
690 tag = None
691 curve = None
692 for line in vector_data:
693 line = line.strip()
694
695 if not line or line.startswith("#"):
696 continue
697
698 if line in tags:
699 tag = line
700 curve = None
701 elif line.startswith("[Curve selected:"):
702 curve = curve_name_map[line.split(':')[1].strip()[:-1]]
703
704 if tag is not None and curve is not None:
705 sets[tag.strip("[]")] = curve
706 tag = None
707 if len(tags) == len(sets):
708 break
709
710 # Data
711 data = {
Alex Gaynorace036d2015-09-24 20:23:08 -0400712 "CAVS": {},
713 "IUT": {},
Simo Sorce917addb2015-04-29 19:41:26 -0400714 }
715 tag = None
716 for line in vector_data:
717 line = line.strip()
718
719 if not line or line.startswith("#"):
720 continue
721
722 if line.startswith("["):
723 tag = line.split()[0][1:]
724 elif line.startswith("COUNT = "):
725 data["COUNT"] = int(line.split("=")[1], 16)
726 elif line.startswith("dsCAVS = "):
727 data["CAVS"]["d"] = int(line.split("=")[1], 16)
728 elif line.startswith("QsCAVSx = "):
729 data["CAVS"]["x"] = int(line.split("=")[1], 16)
730 elif line.startswith("QsCAVSy = "):
731 data["CAVS"]["y"] = int(line.split("=")[1], 16)
732 elif line.startswith("dsIUT = "):
733 data["IUT"]["d"] = int(line.split("=")[1], 16)
734 elif line.startswith("QsIUTx = "):
735 data["IUT"]["x"] = int(line.split("=")[1], 16)
736 elif line.startswith("QsIUTy = "):
737 data["IUT"]["y"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400738 elif line.startswith("OI = "):
739 data["OI"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400740 elif line.startswith("Z = "):
741 data["Z"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400742 elif line.startswith("DKM = "):
743 data["DKM"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400744 elif line.startswith("Result = "):
745 result_str = line.split("=")[1].strip()
746 match = result_rx.match(result_str)
747
748 if match.group(1) == "F":
749 data["fail"] = True
750 else:
751 data["fail"] = False
752 data["errno"] = int(match.group(2))
753
754 data["curve"] = sets[tag]
755
756 vectors.append(data)
757
758 data = {
Alex Gaynorace036d2015-09-24 20:23:08 -0400759 "CAVS": {},
760 "IUT": {},
Simo Sorce917addb2015-04-29 19:41:26 -0400761 }
762
763 return vectors
Simo Sorce7600dee2015-09-22 21:56:20 -0400764
765
766def load_x963_vectors(vector_data):
767 """
768 Loads data out of the X9.63 vector data
769 """
770
771 vectors = []
772
773 # Sets Metadata
774 hashname = None
Alex Gaynorace036d2015-09-24 20:23:08 -0400775 vector = {}
Simo Sorce7600dee2015-09-22 21:56:20 -0400776 for line in vector_data:
777 line = line.strip()
778
779 if line.startswith("[SHA"):
780 hashname = line[1:-1]
781 shared_secret_len = 0
782 shared_info_len = 0
783 key_data_len = 0
784 elif line.startswith("[shared secret length"):
785 shared_secret_len = int(line[1:-1].split("=")[1].strip())
786 elif line.startswith("[SharedInfo length"):
787 shared_info_len = int(line[1:-1].split("=")[1].strip())
788 elif line.startswith("[key data length"):
789 key_data_len = int(line[1:-1].split("=")[1].strip())
790 elif line.startswith("COUNT"):
791 count = int(line.split("=")[1].strip())
792 vector["hash"] = hashname
793 vector["count"] = count
Alex Gaynorace036d2015-09-24 20:23:08 -0400794 vector["shared_secret_length"] = shared_secret_len
795 vector["sharedinfo_length"] = shared_info_len
796 vector["key_data_length"] = key_data_len
Simo Sorce7600dee2015-09-22 21:56:20 -0400797 elif line.startswith("Z"):
798 vector["Z"] = line.split("=")[1].strip()
799 assert math.ceil(shared_secret_len / 8) * 2 == len(vector["Z"])
800 elif line.startswith("SharedInfo"):
801 if shared_info_len != 0:
Alex Gaynorace036d2015-09-24 20:23:08 -0400802 vector["sharedinfo"] = line.split("=")[1].strip()
803 silen = len(vector["sharedinfo"])
Simo Sorce7600dee2015-09-22 21:56:20 -0400804 assert math.ceil(shared_info_len / 8) * 2 == silen
805 elif line.startswith("key_data"):
806 vector["key_data"] = line.split("=")[1].strip()
807 assert math.ceil(key_data_len / 8) * 2 == len(vector["key_data"])
808 vectors.append(vector)
Alex Gaynorace036d2015-09-24 20:23:08 -0400809 vector = {}
Simo Sorce7600dee2015-09-22 21:56:20 -0400810
811 return vectors