blob: 37efc580fe61a1dd526d7248d0418ed0a736ca40 [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:
56 if not supported.kwargs["only_if"](item.funcargs["backend"]):
Paul Kehrerf03334e2014-01-02 23:16:14 -060057 pytest.skip("{0} ({1})".format(
58 supported.kwargs["skip_message"], item.funcargs["backend"]
59 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060060 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060061 raise ValueError("This mark is only available on methods that take a "
62 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060063
64
Alex Gaynor7a489db2014-03-22 15:09:34 -070065@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000066def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070067 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000068 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000069
Alex Stapleton85a791f2014-03-27 16:55:41 +000070 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070071
72
Paul Kehrerfdae0702014-11-27 07:50:46 -100073def load_vectors_from_file(filename, loader, mode="r"):
74 with cryptography_vectors.open_vector_file(filename, mode) as vector_file:
Alex Stapletona39a3192014-03-14 20:03:12 +000075 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060076
77
Alex Gaynord3ce7032013-11-11 14:46:20 -080078def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060079 test_data = None
80 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040081
82 for line in vector_data:
83 line = line.strip()
84
Paul Kehrer749ac5b2013-11-18 18:12:41 -060085 # Blank lines, comments, and section headers are ignored
86 if not line or line.startswith("#") or (line.startswith("[")
87 and line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080088 continue
89
Paul Kehrera43b6692013-11-12 15:35:49 -060090 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060091 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060092 continue
93
Donald Stufft9e1a48b2013-08-09 00:32:30 -040094 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060095 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040096
Paul Kehrer1050ddf2014-01-27 21:04:03 -060097 # Some tests (PBKDF2) contain \0, which should be interpreted as a
98 # null character rather than literal.
99 value = value.replace("\\0", "\0")
100
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400101 # COUNT is a special token that indicates a new block of data
102 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600103 test_data = {}
104 data.append(test_data)
105 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400106 # For all other tokens we simply want the name, value stored in
107 # the dictionary
108 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600109 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400110
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600111 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400112
113
Paul Kehrer1951bf62013-09-15 12:05:43 -0500114def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500115 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500116
117 for line in vector_data:
118 line = line.strip()
119
120 # Blank lines and comments are ignored
121 if not line or line.startswith("#"):
122 continue
123
124 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500125 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500126 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500127 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500128 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500129 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
130 # after a C is found the K+P+C tuple is complete
131 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700132 cryptrec_list.append({
133 "key": key,
134 "plaintext": pt,
135 "ciphertext": ct
136 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400137 else:
138 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500139 return cryptrec_list
140
141
Paul Kehrer69e06522013-10-18 17:28:39 -0500142def load_hash_vectors(vector_data):
143 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500144 key = None
145 msg = None
146 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500147
148 for line in vector_data:
149 line = line.strip()
150
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500151 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500152 continue
153
154 if line.startswith("Len"):
155 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500156 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800157 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500158 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500159 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800160 # In the NIST vectors they have chosen to represent an empty
161 # string as hex 00, which is of course not actually an empty
162 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500163 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
164 elif line.startswith("MD"):
165 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500166 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500167 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800168 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500169 key = None
170 msg = None
171 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500172 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800173 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500174 msg = None
175 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500176 else:
177 raise ValueError("Unknown line in hash vector")
178 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000179
180
181def load_pkcs1_vectors(vector_data):
182 """
183 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000184 """
185 private_key_vector = None
186 public_key_vector = None
187 attr = None
188 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600189 example_vector = None
190 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000191 vectors = []
192 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600193 if (
194 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500195 line.startswith("# OAEP Example") or
196 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600197 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600198 if example_vector:
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
204 attr = None
205 example_vector = collections.defaultdict(list)
206
Paul Kehrer3fe91502014-03-29 12:08:39 -0500207 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600208 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600209 continue
210 elif line.startswith("# Salt"):
211 attr = "salt"
212 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500213 elif line.startswith("# Seed"):
214 attr = "seed"
215 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600216 elif line.startswith("# Signature"):
217 attr = "signature"
218 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500219 elif line.startswith("# Encryption"):
220 attr = "encryption"
221 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600222 elif (
223 example_vector and
224 line.startswith("# =============================================")
225 ):
226 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600227 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600228 example_vector[key] = hex_str
229 examples.append(example_vector)
230 example_vector = None
231 attr = None
232 elif example_vector and line.startswith("#"):
233 continue
234 else:
235 if attr is not None and example_vector is not None:
236 example_vector[attr].append(line.strip())
237 continue
238
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000239 if (
240 line.startswith("# Example") or
241 line.startswith("# =============================================")
242 ):
243 if key:
244 assert private_key_vector
245 assert public_key_vector
246
247 for key, value in six.iteritems(public_key_vector):
248 hex_str = "".join(value).replace(" ", "")
249 public_key_vector[key] = int(hex_str, 16)
250
251 for key, value in six.iteritems(private_key_vector):
252 hex_str = "".join(value).replace(" ", "")
253 private_key_vector[key] = int(hex_str, 16)
254
Paul Kehrerefca2802014-02-17 20:55:13 -0600255 private_key_vector["examples"] = examples
256 examples = []
257
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000258 assert (
259 private_key_vector['public_exponent'] ==
260 public_key_vector['public_exponent']
261 )
262
263 assert (
264 private_key_vector['modulus'] ==
265 public_key_vector['modulus']
266 )
267
268 vectors.append(
269 (private_key_vector, public_key_vector)
270 )
271
272 public_key_vector = collections.defaultdict(list)
273 private_key_vector = collections.defaultdict(list)
274 key = None
275 attr = None
276
277 if private_key_vector is None or public_key_vector is None:
278 continue
279
280 if line.startswith("# Private key"):
281 key = private_key_vector
282 elif line.startswith("# Public key"):
283 key = public_key_vector
284 elif line.startswith("# Modulus:"):
285 attr = "modulus"
286 elif line.startswith("# Public exponent:"):
287 attr = "public_exponent"
288 elif line.startswith("# Exponent:"):
289 if key is public_key_vector:
290 attr = "public_exponent"
291 else:
292 assert key is private_key_vector
293 attr = "private_exponent"
294 elif line.startswith("# Prime 1:"):
295 attr = "p"
296 elif line.startswith("# Prime 2:"):
297 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600298 elif line.startswith("# Prime exponent 1:"):
299 attr = "dmp1"
300 elif line.startswith("# Prime exponent 2:"):
301 attr = "dmq1"
302 elif line.startswith("# Coefficient:"):
303 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000304 elif line.startswith("#"):
305 attr = None
306 else:
307 if key is not None and attr is not None:
308 key[attr].append(line.strip())
309 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400310
311
312def load_rsa_nist_vectors(vector_data):
313 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400314 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400315 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400316 data = []
317
318 for line in vector_data:
319 line = line.strip()
320
321 # Blank lines and section headers are ignored
322 if not line or line.startswith("["):
323 continue
324
325 if line.startswith("# Salt len:"):
326 salt_length = int(line.split(":")[1].strip())
327 continue
328 elif line.startswith("#"):
329 continue
330
331 # Build our data using a simple Key = Value format
332 name, value = [c.strip() for c in line.split("=")]
333
334 if name == "n":
335 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400336 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400337 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400338 elif name == "p":
339 p = int(value, 16)
340 elif name == "q":
341 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400342 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400343 if p is None:
344 test_data = {
345 "modulus": n,
346 "public_exponent": e,
347 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400348 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400349 "fail": False
350 }
351 else:
352 test_data = {
353 "modulus": n,
354 "p": p,
355 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400356 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400357 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400358 if salt_length is not None:
359 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400360 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400361 elif name == "e" and p is not None:
362 test_data["public_exponent"] = int(value, 16)
363 elif name == "d":
364 test_data["private_exponent"] = int(value, 16)
365 elif name == "Result":
366 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400367 # For all other tokens we simply want the name, value stored in
368 # the dictionary
369 else:
370 test_data[name.lower()] = value.encode("ascii")
371
372 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200373
374
375def load_fips_dsa_key_pair_vectors(vector_data):
376 """
377 Loads data out of the FIPS DSA KeyPair vector files.
378 """
379 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200380 # When reading_key_data is set to True it tells the loader to continue
381 # constructing dictionaries. We set reading_key_data to False during the
382 # blocks of the vectors of N=224 because we don't support it.
383 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200384 for line in vector_data:
385 line = line.strip()
386
387 if not line or line.startswith("#"):
388 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200389 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200390 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200391 elif line.startswith("[mod = L=2048, N=224"):
392 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200393 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200394 elif line.startswith("[mod = L=2048, N=256"):
395 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200396 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200397 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200398 continue
399
Mohammed Attia49b92592014-03-12 20:07:05 +0200400 if not reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200401 continue
402
Mohammed Attia49b92592014-03-12 20:07:05 +0200403 elif 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 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
543 if key_data is not None:
544 vectors.append(key_data)
545
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
563 if not line or line.startswith("#"):
564 continue
565
566 curve_match = curve_rx.match(line)
567 if curve_match:
568 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
569 digest_name = "SHA-{0}".format(curve_match.group("sha"))
570
571 elif line.startswith("Msg = "):
572 if data is not None:
573 vectors.append(data)
574
575 hexmsg = line.split("=")[1].strip().encode("ascii")
576
577 data = {
578 "curve": curve_name,
579 "digest_algorithm": digest_name,
580 "message": binascii.unhexlify(hexmsg)
581 }
582
583 elif data is not None:
584 if line.startswith("Qx = "):
585 data["x"] = int(line.split("=")[1], 16)
586 elif line.startswith("Qy = "):
587 data["y"] = int(line.split("=")[1], 16)
588 elif line.startswith("R = "):
589 data["r"] = int(line.split("=")[1], 16)
590 elif line.startswith("S = "):
591 data["s"] = int(line.split("=")[1], 16)
592 elif line.startswith("d = "):
593 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100594 elif line.startswith("Result = "):
595 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100596
597 if data is not None:
598 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100599 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100600
601
602def load_kasvs_dh_vectors(vector_data):
603 """
604 Loads data out of the KASVS key exchange vector data
605 """
606
607 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
608
609 vectors = []
610 data = {
611 "fail_z": False,
612 "fail_agree": False
613 }
614
615 for line in vector_data:
616 line = line.strip()
617
618 if not line or line.startswith("#"):
619 continue
620
621 if line.startswith("P = "):
622 data["p"] = int(line.split("=")[1], 16)
623 elif line.startswith("Q = "):
624 data["q"] = int(line.split("=")[1], 16)
625 elif line.startswith("G = "):
626 data["g"] = int(line.split("=")[1], 16)
627 elif line.startswith("Z = "):
628 z_hex = line.split("=")[1].strip().encode("ascii")
629 data["z"] = binascii.unhexlify(z_hex)
630 elif line.startswith("XstatCAVS = "):
631 data["x1"] = int(line.split("=")[1], 16)
632 elif line.startswith("YstatCAVS = "):
633 data["y1"] = int(line.split("=")[1], 16)
634 elif line.startswith("XstatIUT = "):
635 data["x2"] = int(line.split("=")[1], 16)
636 elif line.startswith("YstatIUT = "):
637 data["y2"] = int(line.split("=")[1], 16)
638 elif line.startswith("Result = "):
639 result_str = line.split("=")[1].strip()
640 match = result_rx.match(result_str)
641
642 if match.group(1) == "F":
643 if int(match.group(2)) in (5, 10):
644 data["fail_z"] = True
645 else:
646 data["fail_agree"] = True
647
648 vectors.append(data)
649
650 data = {
651 "p": data["p"],
652 "q": data["q"],
653 "g": data["g"],
654 "fail_z": False,
655 "fail_agree": False
656 }
657
658 return vectors