blob: bc5bc1eafd901e5e0736e945149c9b4bd0fa1a1a [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
Paul Kehrer60fc8da2013-12-26 20:19:34 -060058def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060059 supported = item.keywords.get("supported")
60 if supported and "backend" in item.funcargs:
61 if not supported.kwargs["only_if"](item.funcargs["backend"]):
Paul Kehrerf03334e2014-01-02 23:16:14 -060062 pytest.skip("{0} ({1})".format(
63 supported.kwargs["skip_message"], item.funcargs["backend"]
64 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060065 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060066 raise ValueError("This mark is only available on methods that take a "
67 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060068
69
Alex Gaynor7a489db2014-03-22 15:09:34 -070070@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000071def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070072 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000073 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000074
Alex Stapleton85a791f2014-03-27 16:55:41 +000075 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070076
77
Paul Kehrerd0dc6a32014-04-30 12:12:50 -050078class _DSSSigValue(univ.Sequence):
Paul Kehrerd3e3df92014-04-30 11:13:17 -050079 componentType = namedtype.NamedTypes(
80 namedtype.NamedType('r', univ.Integer()),
81 namedtype.NamedType('s', univ.Integer())
82 )
Paul Kehrer3fc686e2014-04-30 09:07:27 -050083
84
Paul Kehrer14951f42014-04-30 12:14:48 -050085def der_encode_dsa_signature(r, s):
Paul Kehrerd0dc6a32014-04-30 12:12:50 -050086 sig = _DSSSigValue()
Paul Kehrerd3e3df92014-04-30 11:13:17 -050087 sig.setComponentByName('r', r)
88 sig.setComponentByName('s', s)
89 return encoder.encode(sig)
Paul Kehrer3fc686e2014-04-30 09:07:27 -050090
91
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060092def load_vectors_from_file(filename, loader):
Alex Stapletona39a3192014-03-14 20:03:12 +000093 with cryptography_vectors.open_vector_file(filename) as vector_file:
94 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060095
96
Alex Gaynord3ce7032013-11-11 14:46:20 -080097def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060098 test_data = None
99 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400100
101 for line in vector_data:
102 line = line.strip()
103
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600104 # Blank lines, comments, and section headers are ignored
105 if not line or line.startswith("#") or (line.startswith("[")
106 and line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -0800107 continue
108
Paul Kehrera43b6692013-11-12 15:35:49 -0600109 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600110 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -0600111 continue
112
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400113 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -0600114 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400115
Paul Kehrer1050ddf2014-01-27 21:04:03 -0600116 # Some tests (PBKDF2) contain \0, which should be interpreted as a
117 # null character rather than literal.
118 value = value.replace("\\0", "\0")
119
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400120 # COUNT is a special token that indicates a new block of data
121 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600122 test_data = {}
123 data.append(test_data)
124 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400125 # For all other tokens we simply want the name, value stored in
126 # the dictionary
127 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600128 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400129
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600130 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400131
132
Paul Kehrer1951bf62013-09-15 12:05:43 -0500133def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500134 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500135
136 for line in vector_data:
137 line = line.strip()
138
139 # Blank lines and comments are ignored
140 if not line or line.startswith("#"):
141 continue
142
143 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500144 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500145 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500146 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500147 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500148 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
149 # after a C is found the K+P+C tuple is complete
150 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700151 cryptrec_list.append({
152 "key": key,
153 "plaintext": pt,
154 "ciphertext": ct
155 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400156 else:
157 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500158 return cryptrec_list
159
160
Paul Kehrer69e06522013-10-18 17:28:39 -0500161def load_hash_vectors(vector_data):
162 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500163 key = None
164 msg = None
165 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500166
167 for line in vector_data:
168 line = line.strip()
169
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500170 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500171 continue
172
173 if line.startswith("Len"):
174 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500175 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800176 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500177 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500178 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800179 # In the NIST vectors they have chosen to represent an empty
180 # string as hex 00, which is of course not actually an empty
181 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500182 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
183 elif line.startswith("MD"):
184 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500185 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500186 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800187 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500188 key = None
189 msg = None
190 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500191 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800192 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500193 msg = None
194 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500195 else:
196 raise ValueError("Unknown line in hash vector")
197 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000198
199
200def load_pkcs1_vectors(vector_data):
201 """
202 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000203 """
204 private_key_vector = None
205 public_key_vector = None
206 attr = None
207 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600208 example_vector = None
209 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000210 vectors = []
211 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600212 if (
213 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500214 line.startswith("# OAEP Example") or
215 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600216 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600217 if example_vector:
218 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600219 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600220 example_vector[key] = hex_str
221 examples.append(example_vector)
222
223 attr = None
224 example_vector = collections.defaultdict(list)
225
Paul Kehrer3fe91502014-03-29 12:08:39 -0500226 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600227 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600228 continue
229 elif line.startswith("# Salt"):
230 attr = "salt"
231 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500232 elif line.startswith("# Seed"):
233 attr = "seed"
234 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600235 elif line.startswith("# Signature"):
236 attr = "signature"
237 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500238 elif line.startswith("# Encryption"):
239 attr = "encryption"
240 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600241 elif (
242 example_vector and
243 line.startswith("# =============================================")
244 ):
245 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600246 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600247 example_vector[key] = hex_str
248 examples.append(example_vector)
249 example_vector = None
250 attr = None
251 elif example_vector and line.startswith("#"):
252 continue
253 else:
254 if attr is not None and example_vector is not None:
255 example_vector[attr].append(line.strip())
256 continue
257
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000258 if (
259 line.startswith("# Example") or
260 line.startswith("# =============================================")
261 ):
262 if key:
263 assert private_key_vector
264 assert public_key_vector
265
266 for key, value in six.iteritems(public_key_vector):
267 hex_str = "".join(value).replace(" ", "")
268 public_key_vector[key] = int(hex_str, 16)
269
270 for key, value in six.iteritems(private_key_vector):
271 hex_str = "".join(value).replace(" ", "")
272 private_key_vector[key] = int(hex_str, 16)
273
Paul Kehrerefca2802014-02-17 20:55:13 -0600274 private_key_vector["examples"] = examples
275 examples = []
276
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000277 assert (
278 private_key_vector['public_exponent'] ==
279 public_key_vector['public_exponent']
280 )
281
282 assert (
283 private_key_vector['modulus'] ==
284 public_key_vector['modulus']
285 )
286
287 vectors.append(
288 (private_key_vector, public_key_vector)
289 )
290
291 public_key_vector = collections.defaultdict(list)
292 private_key_vector = collections.defaultdict(list)
293 key = None
294 attr = None
295
296 if private_key_vector is None or public_key_vector is None:
297 continue
298
299 if line.startswith("# Private key"):
300 key = private_key_vector
301 elif line.startswith("# Public key"):
302 key = public_key_vector
303 elif line.startswith("# Modulus:"):
304 attr = "modulus"
305 elif line.startswith("# Public exponent:"):
306 attr = "public_exponent"
307 elif line.startswith("# Exponent:"):
308 if key is public_key_vector:
309 attr = "public_exponent"
310 else:
311 assert key is private_key_vector
312 attr = "private_exponent"
313 elif line.startswith("# Prime 1:"):
314 attr = "p"
315 elif line.startswith("# Prime 2:"):
316 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600317 elif line.startswith("# Prime exponent 1:"):
318 attr = "dmp1"
319 elif line.startswith("# Prime exponent 2:"):
320 attr = "dmq1"
321 elif line.startswith("# Coefficient:"):
322 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000323 elif line.startswith("#"):
324 attr = None
325 else:
326 if key is not None and attr is not None:
327 key[attr].append(line.strip())
328 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400329
330
331def load_rsa_nist_vectors(vector_data):
332 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400333 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400334 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400335 data = []
336
337 for line in vector_data:
338 line = line.strip()
339
340 # Blank lines and section headers are ignored
341 if not line or line.startswith("["):
342 continue
343
344 if line.startswith("# Salt len:"):
345 salt_length = int(line.split(":")[1].strip())
346 continue
347 elif line.startswith("#"):
348 continue
349
350 # Build our data using a simple Key = Value format
351 name, value = [c.strip() for c in line.split("=")]
352
353 if name == "n":
354 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400355 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400356 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400357 elif name == "p":
358 p = int(value, 16)
359 elif name == "q":
360 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400361 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400362 if p is None:
363 test_data = {
364 "modulus": n,
365 "public_exponent": e,
366 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400367 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400368 "fail": False
369 }
370 else:
371 test_data = {
372 "modulus": n,
373 "p": p,
374 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400375 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400376 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400377 if salt_length is not None:
378 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400379 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400380 elif name == "e" and p is not None:
381 test_data["public_exponent"] = int(value, 16)
382 elif name == "d":
383 test_data["private_exponent"] = int(value, 16)
384 elif name == "Result":
385 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400386 # For all other tokens we simply want the name, value stored in
387 # the dictionary
388 else:
389 test_data[name.lower()] = value.encode("ascii")
390
391 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200392
393
394def load_fips_dsa_key_pair_vectors(vector_data):
395 """
396 Loads data out of the FIPS DSA KeyPair vector files.
397 """
398 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200399 # When reading_key_data is set to True it tells the loader to continue
400 # constructing dictionaries. We set reading_key_data to False during the
401 # blocks of the vectors of N=224 because we don't support it.
402 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200403 for line in vector_data:
404 line = line.strip()
405
406 if not line or line.startswith("#"):
407 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200408 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200409 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200410 elif line.startswith("[mod = L=2048, N=224"):
411 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200412 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200413 elif line.startswith("[mod = L=2048, N=256"):
414 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200415 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200416 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200417 continue
418
Mohammed Attia49b92592014-03-12 20:07:05 +0200419 if not reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200420 continue
421
Mohammed Attia49b92592014-03-12 20:07:05 +0200422 elif reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200423 if line.startswith("P"):
424 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200425 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200426 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200427 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200428 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200429 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200430 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200431 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200432 vectors.append({'p': vectors[-1]['p'],
433 'q': vectors[-1]['q'],
434 'g': vectors[-1]['g'],
435 'x': int(line.split("=")[1], 16)
436 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200437 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200438 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200439
440 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100441
442
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200443def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200444 """
445 Loads data out of the FIPS DSA SigVer vector files.
446 """
447 vectors = []
448 sha_regex = re.compile(
449 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
450 )
451 # When reading_key_data is set to True it tells the loader to continue
452 # constructing dictionaries. We set reading_key_data to False during the
453 # blocks of the vectors of N=224 because we don't support it.
454 reading_key_data = True
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200455
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200456 for line in vector_data:
457 line = line.strip()
458
459 if not line or line.startswith("#"):
460 continue
461
462 sha_match = sha_regex.match(line)
463 if sha_match:
464 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
465
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500466 if line.startswith("[mod = L=2048, N=224"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200467 reading_key_data = False
468 continue
Paul Kehrer7ef2f8f2014-04-22 08:37:58 -0500469 elif line.startswith("[mod = L=2048, N=256"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200470 reading_key_data = True
471 continue
472
473 if not reading_key_data or line.startswith("[mod"):
474 continue
475
476 name, value = [c.strip() for c in line.split("=")]
477
478 if name == "P":
479 vectors.append({'p': int(value, 16),
480 'digest_algorithm': digest_algorithm})
481 elif name == "Q":
482 vectors[-1]['q'] = int(value, 16)
483 elif name == "G":
484 vectors[-1]['g'] = int(value, 16)
485 elif name == "Msg" and 'msg' not in vectors[-1]:
486 hexmsg = value.strip().encode("ascii")
487 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
488 elif name == "Msg" and 'msg' in vectors[-1]:
489 hexmsg = value.strip().encode("ascii")
490 vectors.append({'p': vectors[-1]['p'],
491 'q': vectors[-1]['q'],
492 'g': vectors[-1]['g'],
493 'digest_algorithm':
494 vectors[-1]['digest_algorithm'],
495 'msg': binascii.unhexlify(hexmsg)})
496 elif name == "X":
497 vectors[-1]['x'] = int(value, 16)
498 elif name == "Y":
499 vectors[-1]['y'] = int(value, 16)
500 elif name == "R":
501 vectors[-1]['r'] = int(value, 16)
502 elif name == "S":
503 vectors[-1]['s'] = int(value, 16)
504 elif name == "Result":
505 vectors[-1]['result'] = value.split("(")[0].strip()
506
507 return vectors
508
509
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100510# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100511_ECDSA_CURVE_NAMES = {
512 "P-192": "secp192r1",
513 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100514 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100515 "P-384": "secp384r1",
516 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100517
Alex Stapletonc387cf72014-04-13 13:58:02 +0100518 "K-163": "sect163k1",
519 "K-233": "sect233k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100520 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100521 "K-409": "sect409k1",
522 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100523
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100524 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100525 "B-233": "sect233r1",
526 "B-283": "sect283r1",
527 "B-409": "sect409r1",
528 "B-571": "sect571r1",
529}
530
531
Alex Stapletoncf048602014-04-12 12:48:59 +0100532def load_fips_ecdsa_key_pair_vectors(vector_data):
533 """
534 Loads data out of the FIPS ECDSA KeyPair vector files.
535 """
536 vectors = []
537 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100538 for line in vector_data:
539 line = line.strip()
540
541 if not line or line.startswith("#"):
542 continue
543
Alex Stapletonc387cf72014-04-13 13:58:02 +0100544 if line[1:-1] in _ECDSA_CURVE_NAMES:
545 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100546
547 elif line.startswith("d = "):
548 if key_data is not None:
549 vectors.append(key_data)
550
551 key_data = {
552 "curve": curve_name,
553 "d": int(line.split("=")[1], 16)
554 }
555
556 elif key_data is not None:
557 if line.startswith("Qx = "):
558 key_data["x"] = int(line.split("=")[1], 16)
559 elif line.startswith("Qy = "):
560 key_data["y"] = int(line.split("=")[1], 16)
561
562 if key_data is not None:
563 vectors.append(key_data)
564
565 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100566
567
568def load_fips_ecdsa_signing_vectors(vector_data):
569 """
570 Loads data out of the FIPS ECDSA SigGen vector files.
571 """
572 vectors = []
573
574 curve_rx = re.compile(
575 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
576 )
577
578 data = None
579 for line in vector_data:
580 line = line.strip()
581
582 if not line or line.startswith("#"):
583 continue
584
585 curve_match = curve_rx.match(line)
586 if curve_match:
587 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
588 digest_name = "SHA-{0}".format(curve_match.group("sha"))
589
590 elif line.startswith("Msg = "):
591 if data is not None:
592 vectors.append(data)
593
594 hexmsg = line.split("=")[1].strip().encode("ascii")
595
596 data = {
597 "curve": curve_name,
598 "digest_algorithm": digest_name,
599 "message": binascii.unhexlify(hexmsg)
600 }
601
602 elif data is not None:
603 if line.startswith("Qx = "):
604 data["x"] = int(line.split("=")[1], 16)
605 elif line.startswith("Qy = "):
606 data["y"] = int(line.split("=")[1], 16)
607 elif line.startswith("R = "):
608 data["r"] = int(line.split("=")[1], 16)
609 elif line.startswith("S = "):
610 data["s"] = int(line.split("=")[1], 16)
611 elif line.startswith("d = "):
612 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100613 elif line.startswith("Result = "):
614 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100615
616 if data is not None:
617 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100618 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100619
620
621def load_kasvs_dh_vectors(vector_data):
622 """
623 Loads data out of the KASVS key exchange vector data
624 """
625
626 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
627
628 vectors = []
629 data = {
630 "fail_z": False,
631 "fail_agree": False
632 }
633
634 for line in vector_data:
635 line = line.strip()
636
637 if not line or line.startswith("#"):
638 continue
639
640 if line.startswith("P = "):
641 data["p"] = int(line.split("=")[1], 16)
642 elif line.startswith("Q = "):
643 data["q"] = int(line.split("=")[1], 16)
644 elif line.startswith("G = "):
645 data["g"] = int(line.split("=")[1], 16)
646 elif line.startswith("Z = "):
647 z_hex = line.split("=")[1].strip().encode("ascii")
648 data["z"] = binascii.unhexlify(z_hex)
649 elif line.startswith("XstatCAVS = "):
650 data["x1"] = int(line.split("=")[1], 16)
651 elif line.startswith("YstatCAVS = "):
652 data["y1"] = int(line.split("=")[1], 16)
653 elif line.startswith("XstatIUT = "):
654 data["x2"] = int(line.split("=")[1], 16)
655 elif line.startswith("YstatIUT = "):
656 data["y2"] = int(line.split("=")[1], 16)
657 elif line.startswith("Result = "):
658 result_str = line.split("=")[1].strip()
659 match = result_rx.match(result_str)
660
661 if match.group(1) == "F":
662 if int(match.group(2)) in (5, 10):
663 data["fail_z"] = True
664 else:
665 data["fail_agree"] = True
666
667 vectors.append(data)
668
669 data = {
670 "p": data["p"],
671 "q": data["q"],
672 "g": data["g"],
673 "fail_z": False,
674 "fail_agree": False
675 }
676
677 return vectors