blob: acc6c1419af053d58299a18b962d8acadbb9c393 [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(',')]
Paul Kehreraed9e172014-01-19 12:09:27 -060043 selected_backends = []
44 for backend in backend_list:
45 if backend.name in split_names:
46 selected_backends.append(backend)
Paul Kehrerc421e632014-01-18 09:22:21 -060047
Paul Kehreraed9e172014-01-19 12:09:27 -060048 if len(selected_backends) > 0:
49 return selected_backends
Paul Kehrerc421e632014-01-18 09:22:21 -060050 else:
51 raise ValueError(
52 "No backend selected. Tried to select: {0}".format(split_names)
53 )
Paul Kehrer34c075e2014-01-13 21:52:08 -050054
55
Paul Kehrer902d8cf2014-10-25 12:22:10 -070056def skip_if_empty(backend_list, required_interfaces):
57 if not backend_list:
58 pytest.skip(
59 "No backends provided supply the interface: {0}".format(
60 ", ".join(iface.__name__ for iface in required_interfaces)
61 )
62 )
63
64
Paul Kehrer60fc8da2013-12-26 20:19:34 -060065def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060066 supported = item.keywords.get("supported")
67 if supported and "backend" in item.funcargs:
68 if not supported.kwargs["only_if"](item.funcargs["backend"]):
Paul Kehrerf03334e2014-01-02 23:16:14 -060069 pytest.skip("{0} ({1})".format(
70 supported.kwargs["skip_message"], item.funcargs["backend"]
71 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060072 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060073 raise ValueError("This mark is only available on methods that take a "
74 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060075
76
Alex Gaynor7a489db2014-03-22 15:09:34 -070077@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000078def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070079 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000080 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000081
Alex Stapleton85a791f2014-03-27 16:55:41 +000082 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070083
84
Paul Kehrerd0dc6a32014-04-30 12:12:50 -050085class _DSSSigValue(univ.Sequence):
Paul Kehrerd3e3df92014-04-30 11:13:17 -050086 componentType = namedtype.NamedTypes(
87 namedtype.NamedType('r', univ.Integer()),
88 namedtype.NamedType('s', univ.Integer())
89 )
Paul Kehrer3fc686e2014-04-30 09:07:27 -050090
91
Paul Kehrer14951f42014-04-30 12:14:48 -050092def der_encode_dsa_signature(r, s):
Paul Kehrerd0dc6a32014-04-30 12:12:50 -050093 sig = _DSSSigValue()
Paul Kehrerd3e3df92014-04-30 11:13:17 -050094 sig.setComponentByName('r', r)
95 sig.setComponentByName('s', s)
96 return encoder.encode(sig)
Paul Kehrer3fc686e2014-04-30 09:07:27 -050097
98
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060099def load_vectors_from_file(filename, loader):
Alex Stapletona39a3192014-03-14 20:03:12 +0000100 with cryptography_vectors.open_vector_file(filename) as vector_file:
101 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -0600102
103
Alex Gaynord3ce7032013-11-11 14:46:20 -0800104def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600105 test_data = None
106 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400107
108 for line in vector_data:
109 line = line.strip()
110
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600111 # Blank lines, comments, and section headers are ignored
112 if not line or line.startswith("#") or (line.startswith("[")
113 and line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -0800114 continue
115
Paul Kehrera43b6692013-11-12 15:35:49 -0600116 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600117 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -0600118 continue
119
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400120 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -0600121 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400122
Paul Kehrer1050ddf2014-01-27 21:04:03 -0600123 # Some tests (PBKDF2) contain \0, which should be interpreted as a
124 # null character rather than literal.
125 value = value.replace("\\0", "\0")
126
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400127 # COUNT is a special token that indicates a new block of data
128 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600129 test_data = {}
130 data.append(test_data)
131 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400132 # For all other tokens we simply want the name, value stored in
133 # the dictionary
134 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600135 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400136
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600137 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400138
139
Paul Kehrer1951bf62013-09-15 12:05:43 -0500140def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500141 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500142
143 for line in vector_data:
144 line = line.strip()
145
146 # Blank lines and comments are ignored
147 if not line or line.startswith("#"):
148 continue
149
150 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500151 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500152 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500153 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500154 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500155 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
156 # after a C is found the K+P+C tuple is complete
157 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700158 cryptrec_list.append({
159 "key": key,
160 "plaintext": pt,
161 "ciphertext": ct
162 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400163 else:
164 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500165 return cryptrec_list
166
167
Paul Kehrer69e06522013-10-18 17:28:39 -0500168def load_hash_vectors(vector_data):
169 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500170 key = None
171 msg = None
172 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500173
174 for line in vector_data:
175 line = line.strip()
176
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500177 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500178 continue
179
180 if line.startswith("Len"):
181 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500182 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800183 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500184 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500185 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800186 # In the NIST vectors they have chosen to represent an empty
187 # string as hex 00, which is of course not actually an empty
188 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500189 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
190 elif line.startswith("MD"):
191 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500192 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500193 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800194 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500195 key = None
196 msg = None
197 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500198 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800199 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500200 msg = None
201 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500202 else:
203 raise ValueError("Unknown line in hash vector")
204 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000205
206
207def load_pkcs1_vectors(vector_data):
208 """
209 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000210 """
211 private_key_vector = None
212 public_key_vector = None
213 attr = None
214 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600215 example_vector = None
216 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000217 vectors = []
218 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600219 if (
220 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500221 line.startswith("# OAEP Example") or
222 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600223 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600224 if example_vector:
225 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600226 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600227 example_vector[key] = hex_str
228 examples.append(example_vector)
229
230 attr = None
231 example_vector = collections.defaultdict(list)
232
Paul Kehrer3fe91502014-03-29 12:08:39 -0500233 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600234 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600235 continue
236 elif line.startswith("# Salt"):
237 attr = "salt"
238 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500239 elif line.startswith("# Seed"):
240 attr = "seed"
241 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600242 elif line.startswith("# Signature"):
243 attr = "signature"
244 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500245 elif line.startswith("# Encryption"):
246 attr = "encryption"
247 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600248 elif (
249 example_vector and
250 line.startswith("# =============================================")
251 ):
252 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600253 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600254 example_vector[key] = hex_str
255 examples.append(example_vector)
256 example_vector = None
257 attr = None
258 elif example_vector and line.startswith("#"):
259 continue
260 else:
261 if attr is not None and example_vector is not None:
262 example_vector[attr].append(line.strip())
263 continue
264
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000265 if (
266 line.startswith("# Example") or
267 line.startswith("# =============================================")
268 ):
269 if key:
270 assert private_key_vector
271 assert public_key_vector
272
273 for key, value in six.iteritems(public_key_vector):
274 hex_str = "".join(value).replace(" ", "")
275 public_key_vector[key] = int(hex_str, 16)
276
277 for key, value in six.iteritems(private_key_vector):
278 hex_str = "".join(value).replace(" ", "")
279 private_key_vector[key] = int(hex_str, 16)
280
Paul Kehrerefca2802014-02-17 20:55:13 -0600281 private_key_vector["examples"] = examples
282 examples = []
283
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000284 assert (
285 private_key_vector['public_exponent'] ==
286 public_key_vector['public_exponent']
287 )
288
289 assert (
290 private_key_vector['modulus'] ==
291 public_key_vector['modulus']
292 )
293
294 vectors.append(
295 (private_key_vector, public_key_vector)
296 )
297
298 public_key_vector = collections.defaultdict(list)
299 private_key_vector = collections.defaultdict(list)
300 key = None
301 attr = None
302
303 if private_key_vector is None or public_key_vector is None:
304 continue
305
306 if line.startswith("# Private key"):
307 key = private_key_vector
308 elif line.startswith("# Public key"):
309 key = public_key_vector
310 elif line.startswith("# Modulus:"):
311 attr = "modulus"
312 elif line.startswith("# Public exponent:"):
313 attr = "public_exponent"
314 elif line.startswith("# Exponent:"):
315 if key is public_key_vector:
316 attr = "public_exponent"
317 else:
318 assert key is private_key_vector
319 attr = "private_exponent"
320 elif line.startswith("# Prime 1:"):
321 attr = "p"
322 elif line.startswith("# Prime 2:"):
323 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600324 elif line.startswith("# Prime exponent 1:"):
325 attr = "dmp1"
326 elif line.startswith("# Prime exponent 2:"):
327 attr = "dmq1"
328 elif line.startswith("# Coefficient:"):
329 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000330 elif line.startswith("#"):
331 attr = None
332 else:
333 if key is not None and attr is not None:
334 key[attr].append(line.strip())
335 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400336
337
338def load_rsa_nist_vectors(vector_data):
339 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400340 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400341 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400342 data = []
343
344 for line in vector_data:
345 line = line.strip()
346
347 # Blank lines and section headers are ignored
348 if not line or line.startswith("["):
349 continue
350
351 if line.startswith("# Salt len:"):
352 salt_length = int(line.split(":")[1].strip())
353 continue
354 elif line.startswith("#"):
355 continue
356
357 # Build our data using a simple Key = Value format
358 name, value = [c.strip() for c in line.split("=")]
359
360 if name == "n":
361 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400362 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400363 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400364 elif name == "p":
365 p = int(value, 16)
366 elif name == "q":
367 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400368 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400369 if p is None:
370 test_data = {
371 "modulus": n,
372 "public_exponent": e,
373 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400374 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400375 "fail": False
376 }
377 else:
378 test_data = {
379 "modulus": n,
380 "p": p,
381 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400382 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400383 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400384 if salt_length is not None:
385 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400386 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400387 elif name == "e" and p is not None:
388 test_data["public_exponent"] = int(value, 16)
389 elif name == "d":
390 test_data["private_exponent"] = int(value, 16)
391 elif name == "Result":
392 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400393 # For all other tokens we simply want the name, value stored in
394 # the dictionary
395 else:
396 test_data[name.lower()] = value.encode("ascii")
397
398 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200399
400
401def load_fips_dsa_key_pair_vectors(vector_data):
402 """
403 Loads data out of the FIPS DSA KeyPair vector files.
404 """
405 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200406 # When reading_key_data is set to True it tells the loader to continue
407 # constructing dictionaries. We set reading_key_data to False during the
408 # blocks of the vectors of N=224 because we don't support it.
409 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200410 for line in vector_data:
411 line = line.strip()
412
413 if not line or line.startswith("#"):
414 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200415 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200416 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200417 elif line.startswith("[mod = L=2048, N=224"):
418 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200419 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200420 elif line.startswith("[mod = L=2048, N=256"):
421 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200422 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200423 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200424 continue
425
Mohammed Attia49b92592014-03-12 20:07:05 +0200426 if not reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200427 continue
428
Mohammed Attia49b92592014-03-12 20:07:05 +0200429 elif reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200430 if line.startswith("P"):
431 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200432 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200433 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200434 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200435 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200436 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200437 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200438 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200439 vectors.append({'p': vectors[-1]['p'],
440 'q': vectors[-1]['q'],
441 'g': vectors[-1]['g'],
442 'x': int(line.split("=")[1], 16)
443 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200444 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200445 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200446
447 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100448
449
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200450def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200451 """
452 Loads data out of the FIPS DSA SigVer vector files.
453 """
454 vectors = []
455 sha_regex = re.compile(
456 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
457 )
458 # When reading_key_data is set to True it tells the loader to continue
459 # constructing dictionaries. We set reading_key_data to False during the
460 # blocks of the vectors of N=224 because we don't support it.
461 reading_key_data = True
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200462
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200463 for line in vector_data:
464 line = line.strip()
465
466 if not line or line.startswith("#"):
467 continue
468
469 sha_match = sha_regex.match(line)
470 if sha_match:
471 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
472
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500473 if line.startswith("[mod = L=2048, N=224"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200474 reading_key_data = False
475 continue
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500476 elif line.startswith("[mod = L=2048, N=256"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200477 reading_key_data = True
478 continue
479
480 if not reading_key_data or line.startswith("[mod"):
481 continue
482
483 name, value = [c.strip() for c in line.split("=")]
484
485 if name == "P":
486 vectors.append({'p': int(value, 16),
487 'digest_algorithm': digest_algorithm})
488 elif name == "Q":
489 vectors[-1]['q'] = int(value, 16)
490 elif name == "G":
491 vectors[-1]['g'] = int(value, 16)
492 elif name == "Msg" and 'msg' not in vectors[-1]:
493 hexmsg = value.strip().encode("ascii")
494 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
495 elif name == "Msg" and 'msg' in vectors[-1]:
496 hexmsg = value.strip().encode("ascii")
497 vectors.append({'p': vectors[-1]['p'],
498 'q': vectors[-1]['q'],
499 'g': vectors[-1]['g'],
500 'digest_algorithm':
501 vectors[-1]['digest_algorithm'],
502 'msg': binascii.unhexlify(hexmsg)})
503 elif name == "X":
504 vectors[-1]['x'] = int(value, 16)
505 elif name == "Y":
506 vectors[-1]['y'] = int(value, 16)
507 elif name == "R":
508 vectors[-1]['r'] = int(value, 16)
509 elif name == "S":
510 vectors[-1]['s'] = int(value, 16)
511 elif name == "Result":
512 vectors[-1]['result'] = value.split("(")[0].strip()
513
514 return vectors
515
516
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100517# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100518_ECDSA_CURVE_NAMES = {
519 "P-192": "secp192r1",
520 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100521 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100522 "P-384": "secp384r1",
523 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100524
Alex Stapletonc387cf72014-04-13 13:58:02 +0100525 "K-163": "sect163k1",
526 "K-233": "sect233k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100527 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100528 "K-409": "sect409k1",
529 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100530
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100531 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100532 "B-233": "sect233r1",
533 "B-283": "sect283r1",
534 "B-409": "sect409r1",
535 "B-571": "sect571r1",
536}
537
538
Alex Stapletoncf048602014-04-12 12:48:59 +0100539def load_fips_ecdsa_key_pair_vectors(vector_data):
540 """
541 Loads data out of the FIPS ECDSA KeyPair vector files.
542 """
543 vectors = []
544 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100545 for line in vector_data:
546 line = line.strip()
547
548 if not line or line.startswith("#"):
549 continue
550
Alex Stapletonc387cf72014-04-13 13:58:02 +0100551 if line[1:-1] in _ECDSA_CURVE_NAMES:
552 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100553
554 elif line.startswith("d = "):
555 if key_data is not None:
556 vectors.append(key_data)
557
558 key_data = {
559 "curve": curve_name,
560 "d": int(line.split("=")[1], 16)
561 }
562
563 elif key_data is not None:
564 if line.startswith("Qx = "):
565 key_data["x"] = int(line.split("=")[1], 16)
566 elif line.startswith("Qy = "):
567 key_data["y"] = int(line.split("=")[1], 16)
568
569 if key_data is not None:
570 vectors.append(key_data)
571
572 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100573
574
575def load_fips_ecdsa_signing_vectors(vector_data):
576 """
577 Loads data out of the FIPS ECDSA SigGen vector files.
578 """
579 vectors = []
580
581 curve_rx = re.compile(
582 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
583 )
584
585 data = None
586 for line in vector_data:
587 line = line.strip()
588
589 if not line or line.startswith("#"):
590 continue
591
592 curve_match = curve_rx.match(line)
593 if curve_match:
594 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
595 digest_name = "SHA-{0}".format(curve_match.group("sha"))
596
597 elif line.startswith("Msg = "):
598 if data is not None:
599 vectors.append(data)
600
601 hexmsg = line.split("=")[1].strip().encode("ascii")
602
603 data = {
604 "curve": curve_name,
605 "digest_algorithm": digest_name,
606 "message": binascii.unhexlify(hexmsg)
607 }
608
609 elif data is not None:
610 if line.startswith("Qx = "):
611 data["x"] = int(line.split("=")[1], 16)
612 elif line.startswith("Qy = "):
613 data["y"] = int(line.split("=")[1], 16)
614 elif line.startswith("R = "):
615 data["r"] = int(line.split("=")[1], 16)
616 elif line.startswith("S = "):
617 data["s"] = int(line.split("=")[1], 16)
618 elif line.startswith("d = "):
619 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100620 elif line.startswith("Result = "):
621 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100622
623 if data is not None:
624 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100625 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100626
627
628def load_kasvs_dh_vectors(vector_data):
629 """
630 Loads data out of the KASVS key exchange vector data
631 """
632
633 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
634
635 vectors = []
636 data = {
637 "fail_z": False,
638 "fail_agree": False
639 }
640
641 for line in vector_data:
642 line = line.strip()
643
644 if not line or line.startswith("#"):
645 continue
646
647 if line.startswith("P = "):
648 data["p"] = int(line.split("=")[1], 16)
649 elif line.startswith("Q = "):
650 data["q"] = int(line.split("=")[1], 16)
651 elif line.startswith("G = "):
652 data["g"] = int(line.split("=")[1], 16)
653 elif line.startswith("Z = "):
654 z_hex = line.split("=")[1].strip().encode("ascii")
655 data["z"] = binascii.unhexlify(z_hex)
656 elif line.startswith("XstatCAVS = "):
657 data["x1"] = int(line.split("=")[1], 16)
658 elif line.startswith("YstatCAVS = "):
659 data["y1"] = int(line.split("=")[1], 16)
660 elif line.startswith("XstatIUT = "):
661 data["x2"] = int(line.split("=")[1], 16)
662 elif line.startswith("YstatIUT = "):
663 data["y2"] = int(line.split("=")[1], 16)
664 elif line.startswith("Result = "):
665 result_str = line.split("=")[1].strip()
666 match = result_rx.match(result_str)
667
668 if match.group(1) == "F":
669 if int(match.group(2)) in (5, 10):
670 data["fail_z"] = True
671 else:
672 data["fail_agree"] = True
673
674 vectors.append(data)
675
676 data = {
677 "p": data["p"],
678 "q": data["q"],
679 "g": data["g"],
680 "fail_z": False,
681 "fail_agree": False
682 }
683
684 return vectors