blob: 5557ea85dfb4419a5708312e6de5d7c2d427cd64 [file] [log] [blame]
Alex Gaynorf312a5c2013-08-10 15:23:38 -04001# Licensed under the Apache License, Version 2.0 (the "License");
2# you may not use this file except in compliance with the License.
3# You may obtain a copy of the License at
4#
5# http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS,
9# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10# implied.
11# See the License for the specific language governing permissions and
12# limitations under the License.
13
Alex Gaynorc37feed2014-03-08 08:32:56 -080014from __future__ import absolute_import, division, print_function
15
Alex Stapletonc387cf72014-04-13 13:58:02 +010016import binascii
Alex Gaynor36e651c2014-01-27 10:08:35 -080017import collections
Alex Stapletonc387cf72014-04-13 13:58:02 +010018import re
Alex Stapleton707b0082014-04-20 22:24:41 +010019from contextlib import contextmanager
Paul Kehrer90450f32014-03-19 12:37:17 -040020
Paul Kehrera409ae12014-04-30 13:28:28 -050021from pyasn1.codec.der import encoder
Paul Kehrerd3e3df92014-04-30 11:13:17 -050022from pyasn1.type import namedtype, univ
23
Alex Stapletona39a3192014-03-14 20:03:12 +000024import pytest
25
Paul Kehrerafc1ccd2014-03-19 11:49:32 -040026import six
Alex Gaynor2b3f9422013-12-24 21:55:24 -080027
Alex Gaynor7a489db2014-03-22 15:09:34 -070028from cryptography.exceptions import UnsupportedAlgorithm
Alex Gaynor07c4dcc2014-04-05 11:22:07 -070029
Alex Stapletona39a3192014-03-14 20:03:12 +000030import cryptography_vectors
Matthew Iversen68e77c72014-03-13 08:54:43 +110031
Alex Gaynor2b3f9422013-12-24 21:55:24 -080032
Alex Gaynor36e651c2014-01-27 10:08:35 -080033HashVector = collections.namedtuple("HashVector", ["message", "digest"])
34KeyedHashVector = collections.namedtuple(
35 "KeyedHashVector", ["message", "digest", "key"]
36)
37
38
Paul Kehrerc421e632014-01-18 09:22:21 -060039def select_backends(names, backend_list):
40 if names is None:
41 return backend_list
42 split_names = [x.strip() for x in names.split(',')]
43 # this must be duplicated and then removed to preserve the metadata
44 # pytest associates. Appending backends to a new list doesn't seem to work
Paul Kehreraed9e172014-01-19 12:09:27 -060045 selected_backends = []
46 for backend in backend_list:
47 if backend.name in split_names:
48 selected_backends.append(backend)
Paul Kehrerc421e632014-01-18 09:22:21 -060049
Paul Kehreraed9e172014-01-19 12:09:27 -060050 if len(selected_backends) > 0:
51 return selected_backends
Paul Kehrerc421e632014-01-18 09:22:21 -060052 else:
53 raise ValueError(
54 "No backend selected. Tried to select: {0}".format(split_names)
55 )
Paul Kehrer34c075e2014-01-13 21:52:08 -050056
57
Alex Gaynor2b3f9422013-12-24 21:55:24 -080058def check_for_iface(name, iface, item):
59 if name in item.keywords and "backend" in item.funcargs:
60 if not isinstance(item.funcargs["backend"], iface):
61 pytest.skip("{0} backend does not support {1}".format(
62 item.funcargs["backend"], name
63 ))
Donald Stufft9e1a48b2013-08-09 00:32:30 -040064
65
Paul Kehrer60fc8da2013-12-26 20:19:34 -060066def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060067 supported = item.keywords.get("supported")
68 if supported and "backend" in item.funcargs:
69 if not supported.kwargs["only_if"](item.funcargs["backend"]):
Paul Kehrerf03334e2014-01-02 23:16:14 -060070 pytest.skip("{0} ({1})".format(
71 supported.kwargs["skip_message"], item.funcargs["backend"]
72 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060073 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060074 raise ValueError("This mark is only available on methods that take a "
75 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060076
77
Alex Gaynor7a489db2014-03-22 15:09:34 -070078@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000079def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070080 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000081 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000082
Alex Stapleton85a791f2014-03-27 16:55:41 +000083 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070084
85
Paul Kehrerd0dc6a32014-04-30 12:12:50 -050086class _DSSSigValue(univ.Sequence):
Paul Kehrerd3e3df92014-04-30 11:13:17 -050087 componentType = namedtype.NamedTypes(
88 namedtype.NamedType('r', univ.Integer()),
89 namedtype.NamedType('s', univ.Integer())
90 )
Paul Kehrer3fc686e2014-04-30 09:07:27 -050091
92
Paul Kehrer14951f42014-04-30 12:14:48 -050093def der_encode_dsa_signature(r, s):
Paul Kehrerd0dc6a32014-04-30 12:12:50 -050094 sig = _DSSSigValue()
Paul Kehrerd3e3df92014-04-30 11:13:17 -050095 sig.setComponentByName('r', r)
96 sig.setComponentByName('s', s)
97 return encoder.encode(sig)
Paul Kehrer3fc686e2014-04-30 09:07:27 -050098
99
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -0600100def load_vectors_from_file(filename, loader):
Alex Stapletona39a3192014-03-14 20:03:12 +0000101 with cryptography_vectors.open_vector_file(filename) as vector_file:
102 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -0600103
104
Alex Gaynord3ce7032013-11-11 14:46:20 -0800105def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600106 test_data = None
107 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400108
109 for line in vector_data:
110 line = line.strip()
111
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600112 # Blank lines, comments, and section headers are ignored
113 if not line or line.startswith("#") or (line.startswith("[")
114 and line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -0800115 continue
116
Paul Kehrera43b6692013-11-12 15:35:49 -0600117 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600118 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -0600119 continue
120
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400121 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -0600122 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400123
Paul Kehrer1050ddf2014-01-27 21:04:03 -0600124 # Some tests (PBKDF2) contain \0, which should be interpreted as a
125 # null character rather than literal.
126 value = value.replace("\\0", "\0")
127
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400128 # COUNT is a special token that indicates a new block of data
129 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600130 test_data = {}
131 data.append(test_data)
132 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400133 # For all other tokens we simply want the name, value stored in
134 # the dictionary
135 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600136 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400137
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600138 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400139
140
Paul Kehrer1951bf62013-09-15 12:05:43 -0500141def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500142 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500143
144 for line in vector_data:
145 line = line.strip()
146
147 # Blank lines and comments are ignored
148 if not line or line.startswith("#"):
149 continue
150
151 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500152 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500153 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500154 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500155 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500156 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
157 # after a C is found the K+P+C tuple is complete
158 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700159 cryptrec_list.append({
160 "key": key,
161 "plaintext": pt,
162 "ciphertext": ct
163 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400164 else:
165 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500166 return cryptrec_list
167
168
Paul Kehrer69e06522013-10-18 17:28:39 -0500169def load_hash_vectors(vector_data):
170 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500171 key = None
172 msg = None
173 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500174
175 for line in vector_data:
176 line = line.strip()
177
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500178 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500179 continue
180
181 if line.startswith("Len"):
182 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500183 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800184 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500185 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500186 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800187 # In the NIST vectors they have chosen to represent an empty
188 # string as hex 00, which is of course not actually an empty
189 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500190 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
191 elif line.startswith("MD"):
192 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500193 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500194 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800195 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500196 key = None
197 msg = None
198 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500199 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800200 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500201 msg = None
202 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500203 else:
204 raise ValueError("Unknown line in hash vector")
205 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000206
207
208def load_pkcs1_vectors(vector_data):
209 """
210 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000211 """
212 private_key_vector = None
213 public_key_vector = None
214 attr = None
215 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600216 example_vector = None
217 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000218 vectors = []
219 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600220 if (
221 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500222 line.startswith("# OAEP Example") or
223 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600224 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600225 if example_vector:
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
231 attr = None
232 example_vector = collections.defaultdict(list)
233
Paul Kehrer3fe91502014-03-29 12:08:39 -0500234 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600235 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600236 continue
237 elif line.startswith("# Salt"):
238 attr = "salt"
239 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500240 elif line.startswith("# Seed"):
241 attr = "seed"
242 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600243 elif line.startswith("# Signature"):
244 attr = "signature"
245 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500246 elif line.startswith("# Encryption"):
247 attr = "encryption"
248 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600249 elif (
250 example_vector and
251 line.startswith("# =============================================")
252 ):
253 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600254 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600255 example_vector[key] = hex_str
256 examples.append(example_vector)
257 example_vector = None
258 attr = None
259 elif example_vector and line.startswith("#"):
260 continue
261 else:
262 if attr is not None and example_vector is not None:
263 example_vector[attr].append(line.strip())
264 continue
265
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000266 if (
267 line.startswith("# Example") or
268 line.startswith("# =============================================")
269 ):
270 if key:
271 assert private_key_vector
272 assert public_key_vector
273
274 for key, value in six.iteritems(public_key_vector):
275 hex_str = "".join(value).replace(" ", "")
276 public_key_vector[key] = int(hex_str, 16)
277
278 for key, value in six.iteritems(private_key_vector):
279 hex_str = "".join(value).replace(" ", "")
280 private_key_vector[key] = int(hex_str, 16)
281
Paul Kehrerefca2802014-02-17 20:55:13 -0600282 private_key_vector["examples"] = examples
283 examples = []
284
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000285 assert (
286 private_key_vector['public_exponent'] ==
287 public_key_vector['public_exponent']
288 )
289
290 assert (
291 private_key_vector['modulus'] ==
292 public_key_vector['modulus']
293 )
294
295 vectors.append(
296 (private_key_vector, public_key_vector)
297 )
298
299 public_key_vector = collections.defaultdict(list)
300 private_key_vector = collections.defaultdict(list)
301 key = None
302 attr = None
303
304 if private_key_vector is None or public_key_vector is None:
305 continue
306
307 if line.startswith("# Private key"):
308 key = private_key_vector
309 elif line.startswith("# Public key"):
310 key = public_key_vector
311 elif line.startswith("# Modulus:"):
312 attr = "modulus"
313 elif line.startswith("# Public exponent:"):
314 attr = "public_exponent"
315 elif line.startswith("# Exponent:"):
316 if key is public_key_vector:
317 attr = "public_exponent"
318 else:
319 assert key is private_key_vector
320 attr = "private_exponent"
321 elif line.startswith("# Prime 1:"):
322 attr = "p"
323 elif line.startswith("# Prime 2:"):
324 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600325 elif line.startswith("# Prime exponent 1:"):
326 attr = "dmp1"
327 elif line.startswith("# Prime exponent 2:"):
328 attr = "dmq1"
329 elif line.startswith("# Coefficient:"):
330 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000331 elif line.startswith("#"):
332 attr = None
333 else:
334 if key is not None and attr is not None:
335 key[attr].append(line.strip())
336 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400337
338
339def load_rsa_nist_vectors(vector_data):
340 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400341 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400342 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400343 data = []
344
345 for line in vector_data:
346 line = line.strip()
347
348 # Blank lines and section headers are ignored
349 if not line or line.startswith("["):
350 continue
351
352 if line.startswith("# Salt len:"):
353 salt_length = int(line.split(":")[1].strip())
354 continue
355 elif line.startswith("#"):
356 continue
357
358 # Build our data using a simple Key = Value format
359 name, value = [c.strip() for c in line.split("=")]
360
361 if name == "n":
362 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400363 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400364 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400365 elif name == "p":
366 p = int(value, 16)
367 elif name == "q":
368 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400369 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400370 if p is None:
371 test_data = {
372 "modulus": n,
373 "public_exponent": e,
374 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400375 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400376 "fail": False
377 }
378 else:
379 test_data = {
380 "modulus": n,
381 "p": p,
382 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400383 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400384 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400385 if salt_length is not None:
386 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400387 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400388 elif name == "e" and p is not None:
389 test_data["public_exponent"] = int(value, 16)
390 elif name == "d":
391 test_data["private_exponent"] = int(value, 16)
392 elif name == "Result":
393 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400394 # For all other tokens we simply want the name, value stored in
395 # the dictionary
396 else:
397 test_data[name.lower()] = value.encode("ascii")
398
399 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200400
401
402def load_fips_dsa_key_pair_vectors(vector_data):
403 """
404 Loads data out of the FIPS DSA KeyPair vector files.
405 """
406 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200407 # When reading_key_data is set to True it tells the loader to continue
408 # constructing dictionaries. We set reading_key_data to False during the
409 # blocks of the vectors of N=224 because we don't support it.
410 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200411 for line in vector_data:
412 line = line.strip()
413
414 if not line or line.startswith("#"):
415 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200416 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200417 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200418 elif line.startswith("[mod = L=2048, N=224"):
419 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200420 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200421 elif line.startswith("[mod = L=2048, N=256"):
422 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200423 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200424 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200425 continue
426
Mohammed Attia49b92592014-03-12 20:07:05 +0200427 if not reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200428 continue
429
Mohammed Attia49b92592014-03-12 20:07:05 +0200430 elif reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200431 if line.startswith("P"):
432 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200433 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200434 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200435 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200436 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200437 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200438 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200439 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200440 vectors.append({'p': vectors[-1]['p'],
441 'q': vectors[-1]['q'],
442 'g': vectors[-1]['g'],
443 'x': int(line.split("=")[1], 16)
444 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200445 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200446 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200447
448 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100449
450
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200451def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200452 """
453 Loads data out of the FIPS DSA SigVer vector files.
454 """
455 vectors = []
456 sha_regex = re.compile(
457 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
458 )
459 # When reading_key_data is set to True it tells the loader to continue
460 # constructing dictionaries. We set reading_key_data to False during the
461 # blocks of the vectors of N=224 because we don't support it.
462 reading_key_data = True
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200463
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200464 for line in vector_data:
465 line = line.strip()
466
467 if not line or line.startswith("#"):
468 continue
469
470 sha_match = sha_regex.match(line)
471 if sha_match:
472 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
473
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500474 if line.startswith("[mod = L=2048, N=224"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200475 reading_key_data = False
476 continue
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500477 elif line.startswith("[mod = L=2048, N=256"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200478 reading_key_data = True
479 continue
480
481 if not reading_key_data or line.startswith("[mod"):
482 continue
483
484 name, value = [c.strip() for c in line.split("=")]
485
486 if name == "P":
487 vectors.append({'p': int(value, 16),
488 'digest_algorithm': digest_algorithm})
489 elif name == "Q":
490 vectors[-1]['q'] = int(value, 16)
491 elif name == "G":
492 vectors[-1]['g'] = int(value, 16)
493 elif name == "Msg" and 'msg' not in vectors[-1]:
494 hexmsg = value.strip().encode("ascii")
495 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
496 elif name == "Msg" and 'msg' in vectors[-1]:
497 hexmsg = value.strip().encode("ascii")
498 vectors.append({'p': vectors[-1]['p'],
499 'q': vectors[-1]['q'],
500 'g': vectors[-1]['g'],
501 'digest_algorithm':
502 vectors[-1]['digest_algorithm'],
503 'msg': binascii.unhexlify(hexmsg)})
504 elif name == "X":
505 vectors[-1]['x'] = int(value, 16)
506 elif name == "Y":
507 vectors[-1]['y'] = int(value, 16)
508 elif name == "R":
509 vectors[-1]['r'] = int(value, 16)
510 elif name == "S":
511 vectors[-1]['s'] = int(value, 16)
512 elif name == "Result":
513 vectors[-1]['result'] = value.split("(")[0].strip()
514
515 return vectors
516
517
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100518# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100519_ECDSA_CURVE_NAMES = {
520 "P-192": "secp192r1",
521 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100522 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100523 "P-384": "secp384r1",
524 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100525
Alex Stapletonc387cf72014-04-13 13:58:02 +0100526 "K-163": "sect163k1",
527 "K-233": "sect233k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100528 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100529 "K-409": "sect409k1",
530 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100531
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100532 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100533 "B-233": "sect233r1",
534 "B-283": "sect283r1",
535 "B-409": "sect409r1",
536 "B-571": "sect571r1",
537}
538
539
Alex Stapletoncf048602014-04-12 12:48:59 +0100540def load_fips_ecdsa_key_pair_vectors(vector_data):
541 """
542 Loads data out of the FIPS ECDSA KeyPair vector files.
543 """
544 vectors = []
545 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100546 for line in vector_data:
547 line = line.strip()
548
549 if not line or line.startswith("#"):
550 continue
551
Alex Stapletonc387cf72014-04-13 13:58:02 +0100552 if line[1:-1] in _ECDSA_CURVE_NAMES:
553 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100554
555 elif line.startswith("d = "):
556 if key_data is not None:
557 vectors.append(key_data)
558
559 key_data = {
560 "curve": curve_name,
561 "d": int(line.split("=")[1], 16)
562 }
563
564 elif key_data is not None:
565 if line.startswith("Qx = "):
566 key_data["x"] = int(line.split("=")[1], 16)
567 elif line.startswith("Qy = "):
568 key_data["y"] = int(line.split("=")[1], 16)
569
570 if key_data is not None:
571 vectors.append(key_data)
572
573 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100574
575
576def load_fips_ecdsa_signing_vectors(vector_data):
577 """
578 Loads data out of the FIPS ECDSA SigGen vector files.
579 """
580 vectors = []
581
582 curve_rx = re.compile(
583 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
584 )
585
586 data = None
587 for line in vector_data:
588 line = line.strip()
589
590 if not line or line.startswith("#"):
591 continue
592
593 curve_match = curve_rx.match(line)
594 if curve_match:
595 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
596 digest_name = "SHA-{0}".format(curve_match.group("sha"))
597
598 elif line.startswith("Msg = "):
599 if data is not None:
600 vectors.append(data)
601
602 hexmsg = line.split("=")[1].strip().encode("ascii")
603
604 data = {
605 "curve": curve_name,
606 "digest_algorithm": digest_name,
607 "message": binascii.unhexlify(hexmsg)
608 }
609
610 elif data is not None:
611 if line.startswith("Qx = "):
612 data["x"] = int(line.split("=")[1], 16)
613 elif line.startswith("Qy = "):
614 data["y"] = int(line.split("=")[1], 16)
615 elif line.startswith("R = "):
616 data["r"] = int(line.split("=")[1], 16)
617 elif line.startswith("S = "):
618 data["s"] = int(line.split("=")[1], 16)
619 elif line.startswith("d = "):
620 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100621 elif line.startswith("Result = "):
622 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100623
624 if data is not None:
625 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100626 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100627
628
629def load_kasvs_dh_vectors(vector_data):
630 """
631 Loads data out of the KASVS key exchange vector data
632 """
633
634 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
635
636 vectors = []
637 data = {
638 "fail_z": False,
639 "fail_agree": False
640 }
641
642 for line in vector_data:
643 line = line.strip()
644
645 if not line or line.startswith("#"):
646 continue
647
648 if line.startswith("P = "):
649 data["p"] = int(line.split("=")[1], 16)
650 elif line.startswith("Q = "):
651 data["q"] = int(line.split("=")[1], 16)
652 elif line.startswith("G = "):
653 data["g"] = int(line.split("=")[1], 16)
654 elif line.startswith("Z = "):
655 z_hex = line.split("=")[1].strip().encode("ascii")
656 data["z"] = binascii.unhexlify(z_hex)
657 elif line.startswith("XstatCAVS = "):
658 data["x1"] = int(line.split("=")[1], 16)
659 elif line.startswith("YstatCAVS = "):
660 data["y1"] = int(line.split("=")[1], 16)
661 elif line.startswith("XstatIUT = "):
662 data["x2"] = int(line.split("=")[1], 16)
663 elif line.startswith("YstatIUT = "):
664 data["y2"] = int(line.split("=")[1], 16)
665 elif line.startswith("Result = "):
666 result_str = line.split("=")[1].strip()
667 match = result_rx.match(result_str)
668
669 if match.group(1) == "F":
670 if int(match.group(2)) in (5, 10):
671 data["fail_z"] = True
672 else:
673 data["fail_agree"] = True
674
675 vectors.append(data)
676
677 data = {
678 "p": data["p"],
679 "q": data["q"],
680 "g": data["g"],
681 "fail_z": False,
682 "fail_agree": False
683 }
684
685 return vectors