blob: ccc3b7c1bbeaf90a2937d5a7de4b3a3cbe5935d6 [file] [log] [blame]
Alex Gaynor5951f462014-11-16 09:08:42 -08001# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
Alex Gaynorf312a5c2013-08-10 15:23:38 -04004
Alex Gaynorc37feed2014-03-08 08:32:56 -08005from __future__ import absolute_import, division, print_function
6
Alex Stapletonc387cf72014-04-13 13:58:02 +01007import binascii
Alex Gaynor36e651c2014-01-27 10:08:35 -08008import collections
Alex Gaynor2e85a922018-07-16 11:18:33 -04009import json
Simo Sorce7600dee2015-09-22 21:56:20 -040010import math
Alex Gaynor2e85a922018-07-16 11:18:33 -040011import os
Alex Stapletonc387cf72014-04-13 13:58:02 +010012import re
Alex Stapleton707b0082014-04-20 22:24:41 +010013from contextlib import contextmanager
Paul Kehrer90450f32014-03-19 12:37:17 -040014
Alex Stapletona39a3192014-03-14 20:03:12 +000015import pytest
16
Paul Kehrerafc1ccd2014-03-19 11:49:32 -040017import six
Alex Gaynor2b3f9422013-12-24 21:55:24 -080018
Alex Gaynor7a489db2014-03-22 15:09:34 -070019from cryptography.exceptions import UnsupportedAlgorithm
Alex Gaynor07c4dcc2014-04-05 11:22:07 -070020
Alex Stapletona39a3192014-03-14 20:03:12 +000021import cryptography_vectors
Matthew Iversen68e77c72014-03-13 08:54:43 +110022
Alex Gaynor2b3f9422013-12-24 21:55:24 -080023
Alex Gaynor36e651c2014-01-27 10:08:35 -080024HashVector = collections.namedtuple("HashVector", ["message", "digest"])
25KeyedHashVector = collections.namedtuple(
26 "KeyedHashVector", ["message", "digest", "key"]
27)
28
29
Alex Gaynore6055fb2017-06-03 22:02:50 -040030def check_backend_support(backend, item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060031 supported = item.keywords.get("supported")
Alex Gaynore6055fb2017-06-03 22:02:50 -040032 if supported:
Alex Gaynor50ebb482015-07-02 00:21:41 -040033 for mark in supported:
Alex Gaynore6055fb2017-06-03 22:02:50 -040034 if not mark.kwargs["only_if"](backend):
Alex Gaynor50ebb482015-07-02 00:21:41 -040035 pytest.skip("{0} ({1})".format(
Alex Gaynore6055fb2017-06-03 22:02:50 -040036 mark.kwargs["skip_message"], backend
Alex Gaynor50ebb482015-07-02 00:21:41 -040037 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060038
39
Alex Gaynor7a489db2014-03-22 15:09:34 -070040@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000041def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070042 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000043 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000044
Alex Stapleton85a791f2014-03-27 16:55:41 +000045 assert exc_info.value._reason is reason
Alex Gaynor7a489db2014-03-22 15:09:34 -070046
47
Paul Kehrerfdae0702014-11-27 07:50:46 -100048def load_vectors_from_file(filename, loader, mode="r"):
49 with cryptography_vectors.open_vector_file(filename, mode) as vector_file:
Alex Stapletona39a3192014-03-14 20:03:12 +000050 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060051
52
Alex Gaynord3ce7032013-11-11 14:46:20 -080053def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060054 test_data = None
55 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040056
57 for line in vector_data:
58 line = line.strip()
59
Paul Kehrer749ac5b2013-11-18 18:12:41 -060060 # Blank lines, comments, and section headers are ignored
Alex Gaynore0a879f2015-02-15 20:54:34 -080061 if not line or line.startswith("#") or (line.startswith("[") and
62 line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080063 continue
64
Paul Kehrera43b6692013-11-12 15:35:49 -060065 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060066 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060067 continue
68
Donald Stufft9e1a48b2013-08-09 00:32:30 -040069 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060070 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040071
Paul Kehrer1050ddf2014-01-27 21:04:03 -060072 # Some tests (PBKDF2) contain \0, which should be interpreted as a
73 # null character rather than literal.
74 value = value.replace("\\0", "\0")
75
Donald Stufft9e1a48b2013-08-09 00:32:30 -040076 # COUNT is a special token that indicates a new block of data
77 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060078 test_data = {}
79 data.append(test_data)
80 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -040081 # For all other tokens we simply want the name, value stored in
82 # the dictionary
83 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -060084 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -040085
Paul Kehrer749ac5b2013-11-18 18:12:41 -060086 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -040087
88
Paul Kehrer1951bf62013-09-15 12:05:43 -050089def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -050090 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -050091
92 for line in vector_data:
93 line = line.strip()
94
95 # Blank lines and comments are ignored
96 if not line or line.startswith("#"):
97 continue
98
99 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500100 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500101 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500102 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500103 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500104 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
105 # after a C is found the K+P+C tuple is complete
106 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700107 cryptrec_list.append({
108 "key": key,
109 "plaintext": pt,
110 "ciphertext": ct
111 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400112 else:
113 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500114 return cryptrec_list
115
116
Paul Kehrer69e06522013-10-18 17:28:39 -0500117def load_hash_vectors(vector_data):
118 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500119 key = None
120 msg = None
121 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500122
123 for line in vector_data:
124 line = line.strip()
125
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500126 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500127 continue
128
129 if line.startswith("Len"):
130 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500131 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800132 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500133 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500134 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800135 # In the NIST vectors they have chosen to represent an empty
136 # string as hex 00, which is of course not actually an empty
137 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500138 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
139 elif line.startswith("MD"):
140 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500141 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500142 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800143 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500144 key = None
145 msg = None
146 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500147 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800148 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500149 msg = None
150 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500151 else:
152 raise ValueError("Unknown line in hash vector")
153 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000154
155
156def load_pkcs1_vectors(vector_data):
157 """
158 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000159 """
160 private_key_vector = None
161 public_key_vector = None
162 attr = None
163 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600164 example_vector = None
165 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000166 vectors = []
167 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600168 if (
169 line.startswith("# PSS Example") or
Paul Kehrer3fe91502014-03-29 12:08:39 -0500170 line.startswith("# OAEP Example") or
171 line.startswith("# PKCS#1 v1.5")
Paul Kehrer7774a032014-02-17 22:56:55 -0600172 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600173 if example_vector:
174 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600175 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600176 example_vector[key] = hex_str
177 examples.append(example_vector)
178
179 attr = None
180 example_vector = collections.defaultdict(list)
181
Paul Kehrer3fe91502014-03-29 12:08:39 -0500182 if line.startswith("# Message"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600183 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600184 continue
185 elif line.startswith("# Salt"):
186 attr = "salt"
187 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500188 elif line.startswith("# Seed"):
189 attr = "seed"
190 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600191 elif line.startswith("# Signature"):
192 attr = "signature"
193 continue
Paul Kehrer3fe91502014-03-29 12:08:39 -0500194 elif line.startswith("# Encryption"):
195 attr = "encryption"
196 continue
Paul Kehrerefca2802014-02-17 20:55:13 -0600197 elif (
198 example_vector and
199 line.startswith("# =============================================")
200 ):
201 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600202 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600203 example_vector[key] = hex_str
204 examples.append(example_vector)
205 example_vector = None
206 attr = None
207 elif example_vector and line.startswith("#"):
208 continue
209 else:
210 if attr is not None and example_vector is not None:
211 example_vector[attr].append(line.strip())
212 continue
213
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000214 if (
215 line.startswith("# Example") or
216 line.startswith("# =============================================")
217 ):
218 if key:
219 assert private_key_vector
220 assert public_key_vector
221
222 for key, value in six.iteritems(public_key_vector):
223 hex_str = "".join(value).replace(" ", "")
224 public_key_vector[key] = int(hex_str, 16)
225
226 for key, value in six.iteritems(private_key_vector):
227 hex_str = "".join(value).replace(" ", "")
228 private_key_vector[key] = int(hex_str, 16)
229
Paul Kehrerefca2802014-02-17 20:55:13 -0600230 private_key_vector["examples"] = examples
231 examples = []
232
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000233 assert (
234 private_key_vector['public_exponent'] ==
235 public_key_vector['public_exponent']
236 )
237
238 assert (
239 private_key_vector['modulus'] ==
240 public_key_vector['modulus']
241 )
242
243 vectors.append(
244 (private_key_vector, public_key_vector)
245 )
246
247 public_key_vector = collections.defaultdict(list)
248 private_key_vector = collections.defaultdict(list)
249 key = None
250 attr = None
251
252 if private_key_vector is None or public_key_vector is None:
Alex Gaynora87daea2017-10-11 21:36:30 -0400253 # Random garbage to defeat CPython's peephole optimizer so that
254 # coverage records correctly: https://bugs.python.org/issue2506
255 1 + 1
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000256 continue
257
258 if line.startswith("# Private key"):
259 key = private_key_vector
260 elif line.startswith("# Public key"):
261 key = public_key_vector
262 elif line.startswith("# Modulus:"):
263 attr = "modulus"
264 elif line.startswith("# Public exponent:"):
265 attr = "public_exponent"
266 elif line.startswith("# Exponent:"):
267 if key is public_key_vector:
268 attr = "public_exponent"
269 else:
270 assert key is private_key_vector
271 attr = "private_exponent"
272 elif line.startswith("# Prime 1:"):
273 attr = "p"
274 elif line.startswith("# Prime 2:"):
275 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600276 elif line.startswith("# Prime exponent 1:"):
277 attr = "dmp1"
278 elif line.startswith("# Prime exponent 2:"):
279 attr = "dmq1"
280 elif line.startswith("# Coefficient:"):
281 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000282 elif line.startswith("#"):
283 attr = None
284 else:
285 if key is not None and attr is not None:
286 key[attr].append(line.strip())
287 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400288
289
290def load_rsa_nist_vectors(vector_data):
291 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400292 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400293 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400294 data = []
295
296 for line in vector_data:
297 line = line.strip()
298
299 # Blank lines and section headers are ignored
300 if not line or line.startswith("["):
301 continue
302
303 if line.startswith("# Salt len:"):
304 salt_length = int(line.split(":")[1].strip())
305 continue
306 elif line.startswith("#"):
307 continue
308
309 # Build our data using a simple Key = Value format
310 name, value = [c.strip() for c in line.split("=")]
311
312 if name == "n":
313 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400314 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400315 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400316 elif name == "p":
317 p = int(value, 16)
318 elif name == "q":
319 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400320 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400321 if p is None:
322 test_data = {
323 "modulus": n,
324 "public_exponent": e,
325 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400326 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400327 "fail": False
328 }
329 else:
330 test_data = {
331 "modulus": n,
332 "p": p,
333 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400334 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400335 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400336 if salt_length is not None:
337 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400338 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400339 elif name == "e" and p is not None:
340 test_data["public_exponent"] = int(value, 16)
341 elif name == "d":
342 test_data["private_exponent"] = int(value, 16)
343 elif name == "Result":
344 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400345 # For all other tokens we simply want the name, value stored in
346 # the dictionary
347 else:
348 test_data[name.lower()] = value.encode("ascii")
349
350 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200351
352
353def load_fips_dsa_key_pair_vectors(vector_data):
354 """
355 Loads data out of the FIPS DSA KeyPair vector files.
356 """
357 vectors = []
Mohammed Attia987cc702014-03-12 16:07:21 +0200358 for line in vector_data:
359 line = line.strip()
360
Paul Kehrer47a66f12018-03-18 10:12:14 -0400361 if not line or line.startswith("#") or line.startswith("[mod"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200362 continue
Alex Gaynor0fe7db62015-06-27 17:20:59 -0400363
Paul Kehrer47a66f12018-03-18 10:12:14 -0400364 if line.startswith("P"):
365 vectors.append({'p': int(line.split("=")[1], 16)})
366 elif line.startswith("Q"):
367 vectors[-1]['q'] = int(line.split("=")[1], 16)
368 elif line.startswith("G"):
369 vectors[-1]['g'] = int(line.split("=")[1], 16)
370 elif line.startswith("X") and 'x' not in vectors[-1]:
371 vectors[-1]['x'] = int(line.split("=")[1], 16)
372 elif line.startswith("X") and 'x' in vectors[-1]:
373 vectors.append({'p': vectors[-1]['p'],
374 'q': vectors[-1]['q'],
375 'g': vectors[-1]['g'],
376 'x': int(line.split("=")[1], 16)
377 })
378 elif line.startswith("Y"):
379 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200380
381 return vectors
Alex Stapletoncf048602014-04-12 12:48:59 +0100382
383
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200384def load_fips_dsa_sig_vectors(vector_data):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200385 """
386 Loads data out of the FIPS DSA SigVer vector files.
387 """
388 vectors = []
389 sha_regex = re.compile(
390 r"\[mod = L=...., N=..., SHA-(?P<sha>1|224|256|384|512)\]"
391 )
Mohammed Attia3c9e1582014-04-22 14:24:44 +0200392
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200393 for line in vector_data:
394 line = line.strip()
395
396 if not line or line.startswith("#"):
397 continue
398
399 sha_match = sha_regex.match(line)
400 if sha_match:
401 digest_algorithm = "SHA-{0}".format(sha_match.group("sha"))
402
Paul Kehrer47a66f12018-03-18 10:12:14 -0400403 if line.startswith("[mod"):
Mohammed Attia0fb5d852014-04-21 10:31:15 +0200404 continue
405
406 name, value = [c.strip() for c in line.split("=")]
407
408 if name == "P":
409 vectors.append({'p': int(value, 16),
410 'digest_algorithm': digest_algorithm})
411 elif name == "Q":
412 vectors[-1]['q'] = int(value, 16)
413 elif name == "G":
414 vectors[-1]['g'] = int(value, 16)
415 elif name == "Msg" and 'msg' not in vectors[-1]:
416 hexmsg = value.strip().encode("ascii")
417 vectors[-1]['msg'] = binascii.unhexlify(hexmsg)
418 elif name == "Msg" and 'msg' in vectors[-1]:
419 hexmsg = value.strip().encode("ascii")
420 vectors.append({'p': vectors[-1]['p'],
421 'q': vectors[-1]['q'],
422 'g': vectors[-1]['g'],
423 'digest_algorithm':
424 vectors[-1]['digest_algorithm'],
425 'msg': binascii.unhexlify(hexmsg)})
426 elif name == "X":
427 vectors[-1]['x'] = int(value, 16)
428 elif name == "Y":
429 vectors[-1]['y'] = int(value, 16)
430 elif name == "R":
431 vectors[-1]['r'] = int(value, 16)
432 elif name == "S":
433 vectors[-1]['s'] = int(value, 16)
434 elif name == "Result":
435 vectors[-1]['result'] = value.split("(")[0].strip()
436
437 return vectors
438
439
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100440# http://tools.ietf.org/html/rfc4492#appendix-A
Alex Stapletonc387cf72014-04-13 13:58:02 +0100441_ECDSA_CURVE_NAMES = {
442 "P-192": "secp192r1",
443 "P-224": "secp224r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100444 "P-256": "secp256r1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100445 "P-384": "secp384r1",
446 "P-521": "secp521r1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100447
Alex Stapletonc387cf72014-04-13 13:58:02 +0100448 "K-163": "sect163k1",
449 "K-233": "sect233k1",
Alex Stapletonf6a1cf62015-05-03 12:16:19 +0100450 "K-256": "secp256k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100451 "K-283": "sect283k1",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100452 "K-409": "sect409k1",
453 "K-571": "sect571k1",
Alex Stapleton39e300f2014-04-18 22:44:02 +0100454
Alex Stapleton44fe82d2014-04-19 09:44:26 +0100455 "B-163": "sect163r2",
Alex Stapletonc387cf72014-04-13 13:58:02 +0100456 "B-233": "sect233r1",
457 "B-283": "sect283r1",
458 "B-409": "sect409r1",
459 "B-571": "sect571r1",
460}
461
462
Alex Stapletoncf048602014-04-12 12:48:59 +0100463def load_fips_ecdsa_key_pair_vectors(vector_data):
464 """
465 Loads data out of the FIPS ECDSA KeyPair vector files.
466 """
467 vectors = []
468 key_data = None
Alex Stapletoncf048602014-04-12 12:48:59 +0100469 for line in vector_data:
470 line = line.strip()
471
472 if not line or line.startswith("#"):
473 continue
474
Alex Stapletonc387cf72014-04-13 13:58:02 +0100475 if line[1:-1] in _ECDSA_CURVE_NAMES:
476 curve_name = _ECDSA_CURVE_NAMES[line[1:-1]]
Alex Stapletoncf048602014-04-12 12:48:59 +0100477
478 elif line.startswith("d = "):
479 if key_data is not None:
480 vectors.append(key_data)
481
482 key_data = {
483 "curve": curve_name,
484 "d": int(line.split("=")[1], 16)
485 }
486
487 elif key_data is not None:
488 if line.startswith("Qx = "):
489 key_data["x"] = int(line.split("=")[1], 16)
490 elif line.startswith("Qy = "):
491 key_data["y"] = int(line.split("=")[1], 16)
492
Paul Kehrerb60b8dd2015-08-01 19:47:22 +0100493 assert key_data is not None
494 vectors.append(key_data)
Alex Stapletoncf048602014-04-12 12:48:59 +0100495
496 return vectors
Alex Stapletonc387cf72014-04-13 13:58:02 +0100497
498
499def load_fips_ecdsa_signing_vectors(vector_data):
500 """
501 Loads data out of the FIPS ECDSA SigGen vector files.
502 """
503 vectors = []
504
505 curve_rx = re.compile(
506 r"\[(?P<curve>[PKB]-[0-9]{3}),SHA-(?P<sha>1|224|256|384|512)\]"
507 )
508
509 data = None
510 for line in vector_data:
511 line = line.strip()
512
Alex Stapletonc387cf72014-04-13 13:58:02 +0100513 curve_match = curve_rx.match(line)
514 if curve_match:
515 curve_name = _ECDSA_CURVE_NAMES[curve_match.group("curve")]
516 digest_name = "SHA-{0}".format(curve_match.group("sha"))
517
518 elif line.startswith("Msg = "):
519 if data is not None:
520 vectors.append(data)
521
522 hexmsg = line.split("=")[1].strip().encode("ascii")
523
524 data = {
525 "curve": curve_name,
526 "digest_algorithm": digest_name,
527 "message": binascii.unhexlify(hexmsg)
528 }
529
530 elif data is not None:
531 if line.startswith("Qx = "):
532 data["x"] = int(line.split("=")[1], 16)
533 elif line.startswith("Qy = "):
534 data["y"] = int(line.split("=")[1], 16)
535 elif line.startswith("R = "):
536 data["r"] = int(line.split("=")[1], 16)
537 elif line.startswith("S = "):
538 data["s"] = int(line.split("=")[1], 16)
539 elif line.startswith("d = "):
540 data["d"] = int(line.split("=")[1], 16)
Alex Stapleton6f729492014-04-19 09:01:25 +0100541 elif line.startswith("Result = "):
542 data["fail"] = line.split("=")[1].strip()[0] == "F"
Alex Stapletonc387cf72014-04-13 13:58:02 +0100543
Paul Kehrerb60b8dd2015-08-01 19:47:22 +0100544 assert data is not None
545 vectors.append(data)
Alex Stapletonc387cf72014-04-13 13:58:02 +0100546 return vectors
Alex Stapleton839c09d2014-08-10 12:18:02 +0100547
548
549def load_kasvs_dh_vectors(vector_data):
550 """
551 Loads data out of the KASVS key exchange vector data
552 """
553
554 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
555
556 vectors = []
557 data = {
558 "fail_z": False,
559 "fail_agree": False
560 }
561
562 for line in vector_data:
563 line = line.strip()
564
565 if not line or line.startswith("#"):
566 continue
567
568 if line.startswith("P = "):
569 data["p"] = int(line.split("=")[1], 16)
570 elif line.startswith("Q = "):
571 data["q"] = int(line.split("=")[1], 16)
572 elif line.startswith("G = "):
573 data["g"] = int(line.split("=")[1], 16)
574 elif line.startswith("Z = "):
575 z_hex = line.split("=")[1].strip().encode("ascii")
576 data["z"] = binascii.unhexlify(z_hex)
577 elif line.startswith("XstatCAVS = "):
578 data["x1"] = int(line.split("=")[1], 16)
579 elif line.startswith("YstatCAVS = "):
580 data["y1"] = int(line.split("=")[1], 16)
581 elif line.startswith("XstatIUT = "):
582 data["x2"] = int(line.split("=")[1], 16)
583 elif line.startswith("YstatIUT = "):
584 data["y2"] = int(line.split("=")[1], 16)
585 elif line.startswith("Result = "):
586 result_str = line.split("=")[1].strip()
587 match = result_rx.match(result_str)
588
589 if match.group(1) == "F":
590 if int(match.group(2)) in (5, 10):
591 data["fail_z"] = True
592 else:
593 data["fail_agree"] = True
594
595 vectors.append(data)
596
597 data = {
598 "p": data["p"],
599 "q": data["q"],
600 "g": data["g"],
601 "fail_z": False,
602 "fail_agree": False
603 }
604
605 return vectors
Simo Sorce917addb2015-04-29 19:41:26 -0400606
607
608def load_kasvs_ecdh_vectors(vector_data):
609 """
610 Loads data out of the KASVS key exchange vector data
611 """
612
613 curve_name_map = {
614 "P-192": "secp192r1",
615 "P-224": "secp224r1",
616 "P-256": "secp256r1",
617 "P-384": "secp384r1",
618 "P-521": "secp521r1",
619 }
620
621 result_rx = re.compile(r"([FP]) \(([0-9]+) -")
622
623 tags = []
Alex Gaynorace036d2015-09-24 20:23:08 -0400624 sets = {}
Simo Sorce917addb2015-04-29 19:41:26 -0400625 vectors = []
626
627 # find info in header
628 for line in vector_data:
629 line = line.strip()
630
631 if line.startswith("#"):
632 parm = line.split("Parameter set(s) supported:")
633 if len(parm) == 2:
634 names = parm[1].strip().split()
635 for n in names:
636 tags.append("[%s]" % n)
637 break
638
639 # Sets Metadata
640 tag = None
641 curve = None
642 for line in vector_data:
643 line = line.strip()
644
645 if not line or line.startswith("#"):
646 continue
647
648 if line in tags:
649 tag = line
650 curve = None
651 elif line.startswith("[Curve selected:"):
652 curve = curve_name_map[line.split(':')[1].strip()[:-1]]
653
654 if tag is not None and curve is not None:
655 sets[tag.strip("[]")] = curve
656 tag = None
657 if len(tags) == len(sets):
658 break
659
660 # Data
661 data = {
Alex Gaynorace036d2015-09-24 20:23:08 -0400662 "CAVS": {},
663 "IUT": {},
Simo Sorce917addb2015-04-29 19:41:26 -0400664 }
665 tag = None
666 for line in vector_data:
667 line = line.strip()
668
669 if not line or line.startswith("#"):
670 continue
671
672 if line.startswith("["):
673 tag = line.split()[0][1:]
674 elif line.startswith("COUNT = "):
Simo Sorce6e3b1552015-10-13 14:45:21 -0400675 data["COUNT"] = int(line.split("=")[1])
Simo Sorce917addb2015-04-29 19:41:26 -0400676 elif line.startswith("dsCAVS = "):
677 data["CAVS"]["d"] = int(line.split("=")[1], 16)
678 elif line.startswith("QsCAVSx = "):
679 data["CAVS"]["x"] = int(line.split("=")[1], 16)
680 elif line.startswith("QsCAVSy = "):
681 data["CAVS"]["y"] = int(line.split("=")[1], 16)
682 elif line.startswith("dsIUT = "):
683 data["IUT"]["d"] = int(line.split("=")[1], 16)
684 elif line.startswith("QsIUTx = "):
685 data["IUT"]["x"] = int(line.split("=")[1], 16)
686 elif line.startswith("QsIUTy = "):
687 data["IUT"]["y"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400688 elif line.startswith("OI = "):
689 data["OI"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400690 elif line.startswith("Z = "):
691 data["Z"] = int(line.split("=")[1], 16)
Simo Sorce83e563e2015-05-06 10:56:31 -0400692 elif line.startswith("DKM = "):
693 data["DKM"] = int(line.split("=")[1], 16)
Simo Sorce917addb2015-04-29 19:41:26 -0400694 elif line.startswith("Result = "):
695 result_str = line.split("=")[1].strip()
696 match = result_rx.match(result_str)
697
698 if match.group(1) == "F":
699 data["fail"] = True
700 else:
701 data["fail"] = False
702 data["errno"] = int(match.group(2))
703
704 data["curve"] = sets[tag]
705
706 vectors.append(data)
707
708 data = {
Alex Gaynorace036d2015-09-24 20:23:08 -0400709 "CAVS": {},
710 "IUT": {},
Simo Sorce917addb2015-04-29 19:41:26 -0400711 }
712
713 return vectors
Simo Sorce7600dee2015-09-22 21:56:20 -0400714
715
716def load_x963_vectors(vector_data):
717 """
718 Loads data out of the X9.63 vector data
719 """
720
721 vectors = []
722
723 # Sets Metadata
724 hashname = None
Alex Gaynorace036d2015-09-24 20:23:08 -0400725 vector = {}
Simo Sorce7600dee2015-09-22 21:56:20 -0400726 for line in vector_data:
727 line = line.strip()
728
729 if line.startswith("[SHA"):
730 hashname = line[1:-1]
731 shared_secret_len = 0
732 shared_info_len = 0
733 key_data_len = 0
734 elif line.startswith("[shared secret length"):
735 shared_secret_len = int(line[1:-1].split("=")[1].strip())
736 elif line.startswith("[SharedInfo length"):
737 shared_info_len = int(line[1:-1].split("=")[1].strip())
738 elif line.startswith("[key data length"):
739 key_data_len = int(line[1:-1].split("=")[1].strip())
740 elif line.startswith("COUNT"):
741 count = int(line.split("=")[1].strip())
742 vector["hash"] = hashname
743 vector["count"] = count
Alex Gaynorace036d2015-09-24 20:23:08 -0400744 vector["shared_secret_length"] = shared_secret_len
745 vector["sharedinfo_length"] = shared_info_len
746 vector["key_data_length"] = key_data_len
Simo Sorce7600dee2015-09-22 21:56:20 -0400747 elif line.startswith("Z"):
748 vector["Z"] = line.split("=")[1].strip()
749 assert math.ceil(shared_secret_len / 8) * 2 == len(vector["Z"])
750 elif line.startswith("SharedInfo"):
751 if shared_info_len != 0:
Alex Gaynorace036d2015-09-24 20:23:08 -0400752 vector["sharedinfo"] = line.split("=")[1].strip()
753 silen = len(vector["sharedinfo"])
Simo Sorce7600dee2015-09-22 21:56:20 -0400754 assert math.ceil(shared_info_len / 8) * 2 == silen
755 elif line.startswith("key_data"):
756 vector["key_data"] = line.split("=")[1].strip()
757 assert math.ceil(key_data_len / 8) * 2 == len(vector["key_data"])
758 vectors.append(vector)
Alex Gaynorace036d2015-09-24 20:23:08 -0400759 vector = {}
Simo Sorce7600dee2015-09-22 21:56:20 -0400760
761 return vectors
Jaredcd258d52016-04-13 14:03:52 -0700762
763
764def load_nist_kbkdf_vectors(vector_data):
765 """
766 Load NIST SP 800-108 KDF Vectors
767 """
768 vectors = []
769 test_data = None
770 tag = {}
771
772 for line in vector_data:
773 line = line.strip()
774
775 if not line or line.startswith("#"):
776 continue
777
778 if line.startswith("[") and line.endswith("]"):
779 tag_data = line[1:-1]
780 name, value = [c.strip() for c in tag_data.split("=")]
781 if value.endswith('_BITS'):
782 value = int(value.split('_')[0])
783 tag.update({name.lower(): value})
784 continue
785
786 tag.update({name.lower(): value.lower()})
787 elif line.startswith("COUNT="):
788 test_data = dict()
789 test_data.update(tag)
790 vectors.append(test_data)
791 elif line.startswith("L"):
792 name, value = [c.strip() for c in line.split("=")]
793 test_data[name.lower()] = int(value)
794 else:
795 name, value = [c.strip() for c in line.split("=")]
796 test_data[name.lower()] = value.encode("ascii")
797
798 return vectors
Paul Kehrera923b002017-06-20 01:12:35 -1000799
800
801def load_ed25519_vectors(vector_data):
802 data = []
803 for line in vector_data:
804 secret_key, public_key, message, signature, _ = line.split(':')
805 # In the vectors the first element is secret key + public key
806 secret_key = secret_key[0:64]
807 # In the vectors the signature section is signature + message
808 signature = signature[0:128]
809 data.append({
810 "secret_key": secret_key,
811 "public_key": public_key,
812 "message": message,
813 "signature": signature
814 })
815 return data
Paul Kehrer33a41e72017-06-21 01:39:20 -1000816
817
818def load_nist_ccm_vectors(vector_data):
819 test_data = None
820 section_data = None
821 global_data = {}
822 new_section = False
823 data = []
824
825 for line in vector_data:
826 line = line.strip()
827
828 # Blank lines and comments should be ignored
829 if not line or line.startswith("#"):
830 continue
831
832 # Some of the CCM vectors have global values for this. They are always
833 # at the top before the first section header (see: VADT, VNT, VPT)
834 if line.startswith(("Alen", "Plen", "Nlen", "Tlen")):
835 name, value = [c.strip() for c in line.split("=")]
836 global_data[name.lower()] = int(value)
837 continue
838
839 # section headers contain length data we might care about
840 if line.startswith("["):
841 new_section = True
842 section_data = {}
843 section = line[1:-1]
844 items = [c.strip() for c in section.split(",")]
845 for item in items:
846 name, value = [c.strip() for c in item.split("=")]
847 section_data[name.lower()] = int(value)
848 continue
849
850 name, value = [c.strip() for c in line.split("=")]
851
852 if name.lower() in ("key", "nonce") and new_section:
853 section_data[name.lower()] = value.encode("ascii")
854 continue
855
856 new_section = False
857
858 # Payload is sometimes special because these vectors are absurd. Each
859 # example may or may not have a payload. If it does not then the
860 # previous example's payload should be used. We accomplish this by
861 # writing it into the section_data. Because we update each example
862 # with the section data it will be overwritten if a new payload value
863 # is present. NIST should be ashamed of their vector creation.
864 if name.lower() == "payload":
865 section_data[name.lower()] = value.encode("ascii")
866
867 # Result is a special token telling us if the test should pass/fail.
868 # This is only present in the DVPT CCM tests
869 if name.lower() == "result":
870 if value.lower() == "pass":
871 test_data["fail"] = False
872 else:
873 test_data["fail"] = True
874 continue
875
876 # COUNT is a special token that indicates a new block of data
877 if name.lower() == "count":
878 test_data = {}
879 test_data.update(global_data)
880 test_data.update(section_data)
881 data.append(test_data)
882 continue
883 # For all other tokens we simply want the name, value stored in
884 # the dictionary
885 else:
886 test_data[name.lower()] = value.encode("ascii")
887
888 return data
Alex Gaynor2e85a922018-07-16 11:18:33 -0400889
890
891class WycheproofTest(object):
892 def __init__(self, testgroup, testcase):
893 self.testgroup = testgroup
894 self.testcase = testcase
895
896 def __repr__(self):
897 return "<WycheproofTest({!r}, {!r}, tcId={})>".format(
898 self.testgroup, self.testcase, self.testcase["tcId"],
899 )
900
901 @property
902 def valid(self):
903 return self.testcase["result"] == "valid"
904
905 @property
906 def acceptable(self):
907 return self.testcase["result"] == "acceptable"
908
909 def has_flag(self, flag):
910 return flag in self.testcase["flags"]
911
912
913def skip_if_wycheproof_none(wycheproof):
914 # This is factored into its own function so we can easily test both
915 # branches
916 if wycheproof is None:
917 pytest.skip("--wycheproof-root not provided")
918
919
920def load_wycheproof_tests(wycheproof, test_file):
921 path = os.path.join(wycheproof, "testvectors", test_file)
922 with open(path) as f:
923 data = json.load(f)
924 for group in data["testGroups"]:
925 cases = group.pop("tests")
926 for c in cases:
927 yield WycheproofTest(group, c)