blob: 44e16a5754023fc13f812777a1d7a88e625f049c [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 Kehrer902d8cf2014-10-25 12:22:10 -070028def skip_if_empty(backend_list, required_interfaces):
29 if not backend_list:
30 pytest.skip(
31 "No backends provided supply the interface: {0}".format(
32 ", ".join(iface.__name__ for iface in required_interfaces)
33 )
34 )
35
36
Paul Kehrer60fc8da2013-12-26 20:19:34 -060037def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060038 supported = item.keywords.get("supported")
39 if supported and "backend" in item.funcargs:
Alex Gaynor50ebb482015-07-02 00:21:41 -040040 for mark in supported:
41 if not mark.kwargs["only_if"](item.funcargs["backend"]):
42 pytest.skip("{0} ({1})".format(
43 mark.kwargs["skip_message"], item.funcargs["backend"]
44 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060045 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060046 raise ValueError("This mark is only available on methods that take a "
47 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060048
49
Alex Gaynor7a489db2014-03-22 15:09:34 -070050@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000051def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070052 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000053 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000054
Alex Stapleton85a791f2014-03-27 16:55:41 +000055 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070056
57
Paul Kehrerfdae0702014-11-27 07:50:46 -100058def load_vectors_from_file(filename, loader, mode="r"):
59 with cryptography_vectors.open_vector_file(filename, mode) as vector_file:
Alex Stapletona39a3192014-03-14 20:03:12 +000060 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060061
62
Alex Gaynord3ce7032013-11-11 14:46:20 -080063def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060064 test_data = None
65 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040066
67 for line in vector_data:
68 line = line.strip()
69
Paul Kehrer749ac5b2013-11-18 18:12:41 -060070 # Blank lines, comments, and section headers are ignored
Alex Gaynore0a879f2015-02-15 20:54:34 -080071 if not line or line.startswith("#") or (line.startswith("[") and
72 line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080073 continue
74
Paul Kehrera43b6692013-11-12 15:35:49 -060075 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060076 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060077 continue
78
Donald Stufft9e1a48b2013-08-09 00:32:30 -040079 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060080 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040081
Paul Kehrer1050ddf2014-01-27 21:04:03 -060082 # Some tests (PBKDF2) contain \0, which should be interpreted as a
83 # null character rather than literal.
84 value = value.replace("\\0", "\0")
85
Donald Stufft9e1a48b2013-08-09 00:32:30 -040086 # COUNT is a special token that indicates a new block of data
87 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060088 test_data = {}
89 data.append(test_data)
90 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -040091 # For all other tokens we simply want the name, value stored in
92 # the dictionary
93 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -060094 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -040095
Paul Kehrer749ac5b2013-11-18 18:12:41 -060096 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -040097
98
Paul Kehrer1951bf62013-09-15 12:05:43 -050099def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500100 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500101
102 for line in vector_data:
103 line = line.strip()
104
105 # Blank lines and comments are ignored
106 if not line or line.startswith("#"):
107 continue
108
109 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500110 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500111 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500112 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500113 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500114 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
115 # after a C is found the K+P+C tuple is complete
116 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700117 cryptrec_list.append({
118 "key": key,
119 "plaintext": pt,
120 "ciphertext": ct
121 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400122 else:
123 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500124 return cryptrec_list
125
126
Paul Kehrer69e06522013-10-18 17:28:39 -0500127def load_hash_vectors(vector_data):
128 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500129 key = None
130 msg = None
131 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500132
133 for line in vector_data:
134 line = line.strip()
135
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500136 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500137 continue
138
139 if line.startswith("Len"):
140 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500141 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800142 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500143 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500144 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800145 # In the NIST vectors they have chosen to represent an empty
146 # string as hex 00, which is of course not actually an empty
147 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500148 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
149 elif line.startswith("MD"):
150 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500151 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500152 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800153 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500154 key = None
155 msg = None
156 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500157 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800158 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500159 msg = None
160 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500161 else:
162 raise ValueError("Unknown line in hash vector")
163 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000164
165
166def load_pkcs1_vectors(vector_data):
167 """
168 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000169 """
170 private_key_vector = None
171 public_key_vector = None
172 attr = None
173 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600174 example_vector = None
175 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000176 vectors = []
177 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600178 if (
179 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500180 line.startswith("# OAEP Example") or
181 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600182 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600183 if example_vector:
184 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600185 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600186 example_vector[key] = hex_str
187 examples.append(example_vector)
188
189 attr = None
190 example_vector = collections.defaultdict(list)
191
Paul Kehrer3fe91502014-03-29 12:08:39 -0500192 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600193 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600194 continue
195 elif line.startswith("# Salt"):
196 attr = "salt"
197 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500198 elif line.startswith("# Seed"):
199 attr = "seed"
200 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600201 elif line.startswith("# Signature"):
202 attr = "signature"
203 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500204 elif line.startswith("# Encryption"):
205 attr = "encryption"
206 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600207 elif (
208 example_vector and
209 line.startswith("# =============================================")
210 ):
211 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600212 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600213 example_vector[key] = hex_str
214 examples.append(example_vector)
215 example_vector = None
216 attr = None
217 elif example_vector and line.startswith("#"):
218 continue
219 else:
220 if attr is not None and example_vector is not None:
221 example_vector[attr].append(line.strip())
222 continue
223
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000224 if (
225 line.startswith("# Example") or
226 line.startswith("# =============================================")
227 ):
228 if key:
229 assert private_key_vector
230 assert public_key_vector
231
232 for key, value in six.iteritems(public_key_vector):
233 hex_str = "".join(value).replace(" ", "")
234 public_key_vector[key] = int(hex_str, 16)
235
236 for key, value in six.iteritems(private_key_vector):
237 hex_str = "".join(value).replace(" ", "")
238 private_key_vector[key] = int(hex_str, 16)
239
Paul Kehrerefca2802014-02-17 20:55:13 -0600240 private_key_vector["examples"] = examples
241 examples = []
242
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000243 assert (
244 private_key_vector['public_exponent'] ==
245 public_key_vector['public_exponent']
246 )
247
248 assert (
249 private_key_vector['modulus'] ==
250 public_key_vector['modulus']
251 )
252
253 vectors.append(
254 (private_key_vector, public_key_vector)
255 )
256
257 public_key_vector = collections.defaultdict(list)
258 private_key_vector = collections.defaultdict(list)
259 key = None
260 attr = None
261
262 if private_key_vector is None or public_key_vector is None:
263 continue
264
265 if line.startswith("# Private key"):
266 key = private_key_vector
267 elif line.startswith("# Public key"):
268 key = public_key_vector
269 elif line.startswith("# Modulus:"):
270 attr = "modulus"
271 elif line.startswith("# Public exponent:"):
272 attr = "public_exponent"
273 elif line.startswith("# Exponent:"):
274 if key is public_key_vector:
275 attr = "public_exponent"
276 else:
277 assert key is private_key_vector
278 attr = "private_exponent"
279 elif line.startswith("# Prime 1:"):
280 attr = "p"
281 elif line.startswith("# Prime 2:"):
282 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600283 elif line.startswith("# Prime exponent 1:"):
284 attr = "dmp1"
285 elif line.startswith("# Prime exponent 2:"):
286 attr = "dmq1"
287 elif line.startswith("# Coefficient:"):
288 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000289 elif line.startswith("#"):
290 attr = None
291 else:
292 if key is not None and attr is not None:
293 key[attr].append(line.strip())
294 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400295
296
297def load_rsa_nist_vectors(vector_data):
298 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400299 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400300 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400301 data = []
302
303 for line in vector_data:
304 line = line.strip()
305
306 # Blank lines and section headers are ignored
307 if not line or line.startswith("["):
308 continue
309
310 if line.startswith("# Salt len:"):
311 salt_length = int(line.split(":")[1].strip())
312 continue
313 elif line.startswith("#"):
314 continue
315
316 # Build our data using a simple Key = Value format
317 name, value = [c.strip() for c in line.split("=")]
318
319 if name == "n":
320 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400321 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400322 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400323 elif name == "p":
324 p = int(value, 16)
325 elif name == "q":
326 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400327 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400328 if p is None:
329 test_data = {
330 "modulus": n,
331 "public_exponent": e,
332 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400333 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400334 "fail": False
335 }
336 else:
337 test_data = {
338 "modulus": n,
339 "p": p,
340 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400341 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400342 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400343 if salt_length is not None:
344 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400345 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400346 elif name == "e" and p is not None:
347 test_data["public_exponent"] = int(value, 16)
348 elif name == "d":
349 test_data["private_exponent"] = int(value, 16)
350 elif name == "Result":
351 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400352 # For all other tokens we simply want the name, value stored in
353 # the dictionary
354 else:
355 test_data[name.lower()] = value.encode("ascii")
356
357 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200358
359
360def load_fips_dsa_key_pair_vectors(vector_data):
361 """
362 Loads data out of the FIPS DSA KeyPair vector files.
363 """
364 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200365 # When reading_key_data is set to True it tells the loader to continue
366 # constructing dictionaries. We set reading_key_data to False during the
367 # blocks of the vectors of N=224 because we don't support it.
368 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200369 for line in vector_data:
370 line = line.strip()
371
372 if not line or line.startswith("#"):
373 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200374 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200375 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200376 elif line.startswith("[mod = L=2048, N=224"):
377 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200378 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200379 elif line.startswith("[mod = L=2048, N=256"):
380 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200381 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200382 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200383 continue
Alex Gaynor0fe7db62015-06-27 17:20:59 -0400384
385 if reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200386 if line.startswith("P"):
387 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200388 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200389 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200390 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200391 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200392 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200393 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200394 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200395 vectors.append({'p': vectors[-1]['p'],
396 'q': vectors[-1]['q'],
397 'g': vectors[-1]['g'],
398 'x': int(line.split("=")[1], 16)
399 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200400 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200401 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200402
403 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100404
405
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200406def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200407 """
408 Loads data out of the FIPS DSA SigVer vector files.
409 """
410 vectors = []
411 sha_regex = re.compile(
412 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
413 )
414 # When reading_key_data is set to True it tells the loader to continue
415 # constructing dictionaries. We set reading_key_data to False during the
416 # blocks of the vectors of N=224 because we don't support it.
417 reading_key_data = True
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200418
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200419 for line in vector_data:
420 line = line.strip()
421
422 if not line or line.startswith("#"):
423 continue
424
425 sha_match = sha_regex.match(line)
426 if sha_match:
427 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
428
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500429 if line.startswith("[mod = L=2048, N=224"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200430 reading_key_data = False
431 continue
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500432 elif line.startswith("[mod = L=2048, N=256"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200433 reading_key_data = True
434 continue
435
436 if not reading_key_data or line.startswith("[mod"):
437 continue
438
439 name, value = [c.strip() for c in line.split("=")]
440
441 if name == "P":
442 vectors.append({'p': int(value, 16),
443 'digest_algorithm': digest_algorithm})
444 elif name == "Q":
445 vectors[-1]['q'] = int(value, 16)
446 elif name == "G":
447 vectors[-1]['g'] = int(value, 16)
448 elif name == "Msg" and 'msg' not in vectors[-1]:
449 hexmsg = value.strip().encode("ascii")
450 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
451 elif name == "Msg" and 'msg' in vectors[-1]:
452 hexmsg = value.strip().encode("ascii")
453 vectors.append({'p': vectors[-1]['p'],
454 'q': vectors[-1]['q'],
455 'g': vectors[-1]['g'],
456 'digest_algorithm':
457 vectors[-1]['digest_algorithm'],
458 'msg': binascii.unhexlify(hexmsg)})
459 elif name == "X":
460 vectors[-1]['x'] = int(value, 16)
461 elif name == "Y":
462 vectors[-1]['y'] = int(value, 16)
463 elif name == "R":
464 vectors[-1]['r'] = int(value, 16)
465 elif name == "S":
466 vectors[-1]['s'] = int(value, 16)
467 elif name == "Result":
468 vectors[-1]['result'] = value.split("(")[0].strip()
469
470 return vectors
471
472
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100473# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100474_ECDSA_CURVE_NAMES = {
475 "P-192": "secp192r1",
476 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100477 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100478 "P-384": "secp384r1",
479 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100480
Alex Stapletonc387cf72014-04-13 13:58:02 +0100481 "K-163": "sect163k1",
482 "K-233": "sect233k1",
Alex Stapletonf6a1cf62015-05-03 12:16:19 +0100483 "K-256": "secp256k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100484 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100485 "K-409": "sect409k1",
486 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100487
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100488 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100489 "B-233": "sect233r1",
490 "B-283": "sect283r1",
491 "B-409": "sect409r1",
492 "B-571": "sect571r1",
493}
494
495
Alex Stapletoncf048602014-04-12 12:48:59 +0100496def load_fips_ecdsa_key_pair_vectors(vector_data):
497 """
498 Loads data out of the FIPS ECDSA KeyPair vector files.
499 """
500 vectors = []
501 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100502 for line in vector_data:
503 line = line.strip()
504
505 if not line or line.startswith("#"):
506 continue
507
Alex Stapletonc387cf72014-04-13 13:58:02 +0100508 if line[1:-1] in _ECDSA_CURVE_NAMES:
509 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100510
511 elif line.startswith("d = "):
512 if key_data is not None:
513 vectors.append(key_data)
514
515 key_data = {
516 "curve": curve_name,
517 "d": int(line.split("=")[1], 16)
518 }
519
520 elif key_data is not None:
521 if line.startswith("Qx = "):
522 key_data["x"] = int(line.split("=")[1], 16)
523 elif line.startswith("Qy = "):
524 key_data["y"] = int(line.split("=")[1], 16)
525
Paul Kehrerb60b8dd2015-08-01 19:47:22 +0100526 assert key_data is not None
527 vectors.append(key_data)
Alex Stapletoncf048602014-04-12 12:48:59 +0100528
529 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100530
531
532def load_fips_ecdsa_signing_vectors(vector_data):
533 """
534 Loads data out of the FIPS ECDSA SigGen vector files.
535 """
536 vectors = []
537
538 curve_rx = re.compile(
539 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
540 )
541
542 data = None
543 for line in vector_data:
544 line = line.strip()
545
Alex Stapletonc387cf72014-04-13 13:58:02 +0100546 curve_match = curve_rx.match(line)
547 if curve_match:
548 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
549 digest_name = "SHA-{0}".format(curve_match.group("sha"))
550
551 elif line.startswith("Msg = "):
552 if data is not None:
553 vectors.append(data)
554
555 hexmsg = line.split("=")[1].strip().encode("ascii")
556
557 data = {
558 "curve": curve_name,
559 "digest_algorithm": digest_name,
560 "message": binascii.unhexlify(hexmsg)
561 }
562
563 elif data is not None:
564 if line.startswith("Qx = "):
565 data["x"] = int(line.split("=")[1], 16)
566 elif line.startswith("Qy = "):
567 data["y"] = int(line.split("=")[1], 16)
568 elif line.startswith("R = "):
569 data["r"] = int(line.split("=")[1], 16)
570 elif line.startswith("S = "):
571 data["s"] = int(line.split("=")[1], 16)
572 elif line.startswith("d = "):
573 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100574 elif line.startswith("Result = "):
575 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100576
Paul Kehrerb60b8dd2015-08-01 19:47:22 +0100577 assert data is not None
578 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100579 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100580
581
582def load_kasvs_dh_vectors(vector_data):
583 """
584 Loads data out of the KASVS key exchange vector data
585 """
586
587 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
588
589 vectors = []
590 data = {
591 "fail_z": False,
592 "fail_agree": False
593 }
594
595 for line in vector_data:
596 line = line.strip()
597
598 if not line or line.startswith("#"):
599 continue
600
601 if line.startswith("P = "):
602 data["p"] = int(line.split("=")[1], 16)
603 elif line.startswith("Q = "):
604 data["q"] = int(line.split("=")[1], 16)
605 elif line.startswith("G = "):
606 data["g"] = int(line.split("=")[1], 16)
607 elif line.startswith("Z = "):
608 z_hex = line.split("=")[1].strip().encode("ascii")
609 data["z"] = binascii.unhexlify(z_hex)
610 elif line.startswith("XstatCAVS = "):
611 data["x1"] = int(line.split("=")[1], 16)
612 elif line.startswith("YstatCAVS = "):
613 data["y1"] = int(line.split("=")[1], 16)
614 elif line.startswith("XstatIUT = "):
615 data["x2"] = int(line.split("=")[1], 16)
616 elif line.startswith("YstatIUT = "):
617 data["y2"] = int(line.split("=")[1], 16)
618 elif line.startswith("Result = "):
619 result_str = line.split("=")[1].strip()
620 match = result_rx.match(result_str)
621
622 if match.group(1) == "F":
623 if int(match.group(2)) in (5, 10):
624 data["fail_z"] = True
625 else:
626 data["fail_agree"] = True
627
628 vectors.append(data)
629
630 data = {
631 "p": data["p"],
632 "q": data["q"],
633 "g": data["g"],
634 "fail_z": False,
635 "fail_agree": False
636 }
637
638 return vectors
Simo Sorce917addb2015-04-29 19:41:26 -0400639
640
641def load_kasvs_ecdh_vectors(vector_data):
642 """
643 Loads data out of the KASVS key exchange vector data
644 """
645
646 curve_name_map = {
647 "P-192": "secp192r1",
648 "P-224": "secp224r1",
649 "P-256": "secp256r1",
650 "P-384": "secp384r1",
651 "P-521": "secp521r1",
652 }
653
654 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
655
656 tags = []
Alex Gaynorace036d2015-09-24 20:23:08 -0400657 sets = {}
Simo Sorce917addb2015-04-29 19:41:26 -0400658 vectors = []
659
660 # find info in header
661 for line in vector_data:
662 line = line.strip()
663
664 if line.startswith("#"):
665 parm = line.split("Parameter set(s) supported:")
666 if len(parm) == 2:
667 names = parm[1].strip().split()
668 for n in names:
669 tags.append("[%s]" % n)
670 break
671
672 # Sets Metadata
673 tag = None
674 curve = None
675 for line in vector_data:
676 line = line.strip()
677
678 if not line or line.startswith("#"):
679 continue
680
681 if line in tags:
682 tag = line
683 curve = None
684 elif line.startswith("[Curve selected:"):
685 curve = curve_name_map[line.split(':')[1].strip()[:-1]]
686
687 if tag is not None and curve is not None:
688 sets[tag.strip("[]")] = curve
689 tag = None
690 if len(tags) == len(sets):
691 break
692
693 # Data
694 data = {
Alex Gaynorace036d2015-09-24 20:23:08 -0400695 "CAVS": {},
696 "IUT": {},
Simo Sorce917addb2015-04-29 19:41:26 -0400697 }
698 tag = None
699 for line in vector_data:
700 line = line.strip()
701
702 if not line or line.startswith("#"):
703 continue
704
705 if line.startswith("["):
706 tag = line.split()[0][1:]
707 elif line.startswith("COUNT = "):
Simo Sorce6e3b1552015-10-13 14:45:21 -0400708 data["COUNT"] = int(line.split("=")[1])
Simo Sorce917addb2015-04-29 19:41:26 -0400709 elif line.startswith("dsCAVS = "):
710 data["CAVS"]["d"] = int(line.split("=")[1], 16)
711 elif line.startswith("QsCAVSx = "):
712 data["CAVS"]["x"] = int(line.split("=")[1], 16)
713 elif line.startswith("QsCAVSy = "):
714 data["CAVS"]["y"] = int(line.split("=")[1], 16)
715 elif line.startswith("dsIUT = "):
716 data["IUT"]["d"] = int(line.split("=")[1], 16)
717 elif line.startswith("QsIUTx = "):
718 data["IUT"]["x"] = int(line.split("=")[1], 16)
719 elif line.startswith("QsIUTy = "):
720 data["IUT"]["y"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400721 elif line.startswith("OI = "):
722 data["OI"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400723 elif line.startswith("Z = "):
724 data["Z"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400725 elif line.startswith("DKM = "):
726 data["DKM"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400727 elif line.startswith("Result = "):
728 result_str = line.split("=")[1].strip()
729 match = result_rx.match(result_str)
730
731 if match.group(1) == "F":
732 data["fail"] = True
733 else:
734 data["fail"] = False
735 data["errno"] = int(match.group(2))
736
737 data["curve"] = sets[tag]
738
739 vectors.append(data)
740
741 data = {
Alex Gaynorace036d2015-09-24 20:23:08 -0400742 "CAVS": {},
743 "IUT": {},
Simo Sorce917addb2015-04-29 19:41:26 -0400744 }
745
746 return vectors
Simo Sorce7600dee2015-09-22 21:56:20 -0400747
748
749def load_x963_vectors(vector_data):
750 """
751 Loads data out of the X9.63 vector data
752 """
753
754 vectors = []
755
756 # Sets Metadata
757 hashname = None
Alex Gaynorace036d2015-09-24 20:23:08 -0400758 vector = {}
Simo Sorce7600dee2015-09-22 21:56:20 -0400759 for line in vector_data:
760 line = line.strip()
761
762 if line.startswith("[SHA"):
763 hashname = line[1:-1]
764 shared_secret_len = 0
765 shared_info_len = 0
766 key_data_len = 0
767 elif line.startswith("[shared secret length"):
768 shared_secret_len = int(line[1:-1].split("=")[1].strip())
769 elif line.startswith("[SharedInfo length"):
770 shared_info_len = int(line[1:-1].split("=")[1].strip())
771 elif line.startswith("[key data length"):
772 key_data_len = int(line[1:-1].split("=")[1].strip())
773 elif line.startswith("COUNT"):
774 count = int(line.split("=")[1].strip())
775 vector["hash"] = hashname
776 vector["count"] = count
Alex Gaynorace036d2015-09-24 20:23:08 -0400777 vector["shared_secret_length"] = shared_secret_len
778 vector["sharedinfo_length"] = shared_info_len
779 vector["key_data_length"] = key_data_len
Simo Sorce7600dee2015-09-22 21:56:20 -0400780 elif line.startswith("Z"):
781 vector["Z"] = line.split("=")[1].strip()
782 assert math.ceil(shared_secret_len / 8) * 2 == len(vector["Z"])
783 elif line.startswith("SharedInfo"):
784 if shared_info_len != 0:
Alex Gaynorace036d2015-09-24 20:23:08 -0400785 vector["sharedinfo"] = line.split("=")[1].strip()
786 silen = len(vector["sharedinfo"])
Simo Sorce7600dee2015-09-22 21:56:20 -0400787 assert math.ceil(shared_info_len / 8) * 2 == silen
788 elif line.startswith("key_data"):
789 vector["key_data"] = line.split("=")[1].strip()
790 assert math.ceil(key_data_len / 8) * 2 == len(vector["key_data"])
791 vectors.append(vector)
Alex Gaynorace036d2015-09-24 20:23:08 -0400792 vector = {}
Simo Sorce7600dee2015-09-22 21:56:20 -0400793
794 return vectors
Jaredcd258d52016-04-13 14:03:52 -0700795
796
797def load_nist_kbkdf_vectors(vector_data):
798 """
799 Load NIST SP 800-108 KDF Vectors
800 """
801 vectors = []
802 test_data = None
803 tag = {}
804
805 for line in vector_data:
806 line = line.strip()
807
808 if not line or line.startswith("#"):
809 continue
810
811 if line.startswith("[") and line.endswith("]"):
812 tag_data = line[1:-1]
813 name, value = [c.strip() for c in tag_data.split("=")]
814 if value.endswith('_BITS'):
815 value = int(value.split('_')[0])
816 tag.update({name.lower(): value})
817 continue
818
819 tag.update({name.lower(): value.lower()})
820 elif line.startswith("COUNT="):
821 test_data = dict()
822 test_data.update(tag)
823 vectors.append(test_data)
824 elif line.startswith("L"):
825 name, value = [c.strip() for c in line.split("=")]
826 test_data[name.lower()] = int(value)
827 else:
828 name, value = [c.strip() for c in line.split("=")]
829 test_data[name.lower()] = value.encode("ascii")
830
831 return vectors