blob: 3e5ea5f3e0e5e329e2cbe82f28b312a167129a69 [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 Gaynor36e651c2014-01-27 10:08:35 -080016import collections
Alex Gaynor7a489db2014-03-22 15:09:34 -070017from contextlib import contextmanager
Paul Kehrer90450f32014-03-19 12:37:17 -040018
Alex Stapletona39a3192014-03-14 20:03:12 +000019import pytest
20
Paul Kehrerafc1ccd2014-03-19 11:49:32 -040021import six
Alex Gaynor2b3f9422013-12-24 21:55:24 -080022
Alex Gaynor7a489db2014-03-22 15:09:34 -070023from cryptography.exceptions import UnsupportedAlgorithm
Alex Stapletona39a3192014-03-14 20:03:12 +000024import cryptography_vectors
Matthew Iversen68e77c72014-03-13 08:54:43 +110025
Alex Gaynor2b3f9422013-12-24 21:55:24 -080026
Alex Gaynor36e651c2014-01-27 10:08:35 -080027HashVector = collections.namedtuple("HashVector", ["message", "digest"])
28KeyedHashVector = collections.namedtuple(
29 "KeyedHashVector", ["message", "digest", "key"]
30)
31
32
Paul Kehrerc421e632014-01-18 09:22:21 -060033def select_backends(names, backend_list):
34 if names is None:
35 return backend_list
36 split_names = [x.strip() for x in names.split(',')]
37 # this must be duplicated and then removed to preserve the metadata
38 # pytest associates. Appending backends to a new list doesn't seem to work
Paul Kehreraed9e172014-01-19 12:09:27 -060039 selected_backends = []
40 for backend in backend_list:
41 if backend.name in split_names:
42 selected_backends.append(backend)
Paul Kehrerc421e632014-01-18 09:22:21 -060043
Paul Kehreraed9e172014-01-19 12:09:27 -060044 if len(selected_backends) > 0:
45 return selected_backends
Paul Kehrerc421e632014-01-18 09:22:21 -060046 else:
47 raise ValueError(
48 "No backend selected. Tried to select: {0}".format(split_names)
49 )
Paul Kehrer34c075e2014-01-13 21:52:08 -050050
51
Alex Gaynor2b3f9422013-12-24 21:55:24 -080052def check_for_iface(name, iface, item):
53 if name in item.keywords and "backend" in item.funcargs:
54 if not isinstance(item.funcargs["backend"], iface):
55 pytest.skip("{0} backend does not support {1}".format(
56 item.funcargs["backend"], name
57 ))
Donald Stufft9e1a48b2013-08-09 00:32:30 -040058
59
Paul Kehrer60fc8da2013-12-26 20:19:34 -060060def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060061 supported = item.keywords.get("supported")
62 if supported and "backend" in item.funcargs:
63 if not supported.kwargs["only_if"](item.funcargs["backend"]):
Paul Kehrerf03334e2014-01-02 23:16:14 -060064 pytest.skip("{0} ({1})".format(
65 supported.kwargs["skip_message"], item.funcargs["backend"]
66 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060067 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060068 raise ValueError("This mark is only available on methods that take a "
69 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060070
71
Alex Gaynor7a489db2014-03-22 15:09:34 -070072@contextmanager
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000073def raises_unsupported_algorithm(reason):
Alex Gaynor7a489db2014-03-22 15:09:34 -070074 with pytest.raises(UnsupportedAlgorithm) as exc_info:
Alex Stapleton112963e2014-03-26 17:39:29 +000075 yield exc_info
Alex Stapleton5e4c8c32014-03-27 16:38:00 +000076
77 if exc_info.value._reason is not reason:
78 pytest.fail("Did not get expected reason tag for UnsupportedAlgorithm")
Alex Gaynor7a489db2014-03-22 15:09:34 -070079
80
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060081def load_vectors_from_file(filename, loader):
Alex Stapletona39a3192014-03-14 20:03:12 +000082 with cryptography_vectors.open_vector_file(filename) as vector_file:
83 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060084
85
Alex Gaynord3ce7032013-11-11 14:46:20 -080086def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060087 test_data = None
88 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040089
90 for line in vector_data:
91 line = line.strip()
92
Paul Kehrer749ac5b2013-11-18 18:12:41 -060093 # Blank lines, comments, and section headers are ignored
94 if not line or line.startswith("#") or (line.startswith("[")
95 and line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080096 continue
97
Paul Kehrera43b6692013-11-12 15:35:49 -060098 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060099 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -0600100 continue
101
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400102 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -0600103 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400104
Paul Kehrer1050ddf2014-01-27 21:04:03 -0600105 # Some tests (PBKDF2) contain \0, which should be interpreted as a
106 # null character rather than literal.
107 value = value.replace("\\0", "\0")
108
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400109 # COUNT is a special token that indicates a new block of data
110 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600111 test_data = {}
112 data.append(test_data)
113 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400114 # For all other tokens we simply want the name, value stored in
115 # the dictionary
116 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600117 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400118
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600119 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400120
121
Paul Kehrer1951bf62013-09-15 12:05:43 -0500122def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500123 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500124
125 for line in vector_data:
126 line = line.strip()
127
128 # Blank lines and comments are ignored
129 if not line or line.startswith("#"):
130 continue
131
132 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500133 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500134 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500135 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500136 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500137 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
138 # after a C is found the K+P+C tuple is complete
139 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700140 cryptrec_list.append({
141 "key": key,
142 "plaintext": pt,
143 "ciphertext": ct
144 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400145 else:
146 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500147 return cryptrec_list
148
149
Paul Kehrer69e06522013-10-18 17:28:39 -0500150def load_hash_vectors(vector_data):
151 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500152 key = None
153 msg = None
154 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500155
156 for line in vector_data:
157 line = line.strip()
158
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500159 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500160 continue
161
162 if line.startswith("Len"):
163 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500164 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800165 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500166 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500167 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800168 # In the NIST vectors they have chosen to represent an empty
169 # string as hex 00, which is of course not actually an empty
170 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500171 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
172 elif line.startswith("MD"):
173 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500174 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500175 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800176 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500177 key = None
178 msg = None
179 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500180 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800181 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500182 msg = None
183 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500184 else:
185 raise ValueError("Unknown line in hash vector")
186 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000187
188
189def load_pkcs1_vectors(vector_data):
190 """
191 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000192 """
193 private_key_vector = None
194 public_key_vector = None
195 attr = None
196 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600197 example_vector = None
198 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000199 vectors = []
200 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600201 if (
202 line.startswith("# PSS Example") or
203 line.startswith("# PKCS#1 v1.5 Signature")
204 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600205 if example_vector:
206 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600207 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600208 example_vector[key] = hex_str
209 examples.append(example_vector)
210
211 attr = None
212 example_vector = collections.defaultdict(list)
213
214 if line.startswith("# Message to be signed"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600215 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600216 continue
217 elif line.startswith("# Salt"):
218 attr = "salt"
219 continue
220 elif line.startswith("# Signature"):
221 attr = "signature"
222 continue
223 elif (
224 example_vector and
225 line.startswith("# =============================================")
226 ):
227 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600228 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600229 example_vector[key] = hex_str
230 examples.append(example_vector)
231 example_vector = None
232 attr = None
233 elif example_vector and line.startswith("#"):
234 continue
235 else:
236 if attr is not None and example_vector is not None:
237 example_vector[attr].append(line.strip())
238 continue
239
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000240 if (
241 line.startswith("# Example") or
242 line.startswith("# =============================================")
243 ):
244 if key:
245 assert private_key_vector
246 assert public_key_vector
247
248 for key, value in six.iteritems(public_key_vector):
249 hex_str = "".join(value).replace(" ", "")
250 public_key_vector[key] = int(hex_str, 16)
251
252 for key, value in six.iteritems(private_key_vector):
253 hex_str = "".join(value).replace(" ", "")
254 private_key_vector[key] = int(hex_str, 16)
255
Paul Kehrerefca2802014-02-17 20:55:13 -0600256 private_key_vector["examples"] = examples
257 examples = []
258
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000259 assert (
260 private_key_vector['public_exponent'] ==
261 public_key_vector['public_exponent']
262 )
263
264 assert (
265 private_key_vector['modulus'] ==
266 public_key_vector['modulus']
267 )
268
269 vectors.append(
270 (private_key_vector, public_key_vector)
271 )
272
273 public_key_vector = collections.defaultdict(list)
274 private_key_vector = collections.defaultdict(list)
275 key = None
276 attr = None
277
278 if private_key_vector is None or public_key_vector is None:
279 continue
280
281 if line.startswith("# Private key"):
282 key = private_key_vector
283 elif line.startswith("# Public key"):
284 key = public_key_vector
285 elif line.startswith("# Modulus:"):
286 attr = "modulus"
287 elif line.startswith("# Public exponent:"):
288 attr = "public_exponent"
289 elif line.startswith("# Exponent:"):
290 if key is public_key_vector:
291 attr = "public_exponent"
292 else:
293 assert key is private_key_vector
294 attr = "private_exponent"
295 elif line.startswith("# Prime 1:"):
296 attr = "p"
297 elif line.startswith("# Prime 2:"):
298 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600299 elif line.startswith("# Prime exponent 1:"):
300 attr = "dmp1"
301 elif line.startswith("# Prime exponent 2:"):
302 attr = "dmq1"
303 elif line.startswith("# Coefficient:"):
304 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000305 elif line.startswith("#"):
306 attr = None
307 else:
308 if key is not None and attr is not None:
309 key[attr].append(line.strip())
310 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400311
312
313def load_rsa_nist_vectors(vector_data):
314 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400315 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400316 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400317 data = []
318
319 for line in vector_data:
320 line = line.strip()
321
322 # Blank lines and section headers are ignored
323 if not line or line.startswith("["):
324 continue
325
326 if line.startswith("# Salt len:"):
327 salt_length = int(line.split(":")[1].strip())
328 continue
329 elif line.startswith("#"):
330 continue
331
332 # Build our data using a simple Key = Value format
333 name, value = [c.strip() for c in line.split("=")]
334
335 if name == "n":
336 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400337 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400338 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400339 elif name == "p":
340 p = int(value, 16)
341 elif name == "q":
342 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400343 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400344 if p is None:
345 test_data = {
346 "modulus": n,
347 "public_exponent": e,
348 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400349 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400350 "fail": False
351 }
352 else:
353 test_data = {
354 "modulus": n,
355 "p": p,
356 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400357 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400358 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400359 if salt_length is not None:
360 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400361 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400362 elif name == "e" and p is not None:
363 test_data["public_exponent"] = int(value, 16)
364 elif name == "d":
365 test_data["private_exponent"] = int(value, 16)
366 elif name == "Result":
367 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400368 # For all other tokens we simply want the name, value stored in
369 # the dictionary
370 else:
371 test_data[name.lower()] = value.encode("ascii")
372
373 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200374
375
376def load_fips_dsa_key_pair_vectors(vector_data):
377 """
378 Loads data out of the FIPS DSA KeyPair vector files.
379 """
380 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200381 # When reading_key_data is set to True it tells the loader to continue
382 # constructing dictionaries. We set reading_key_data to False during the
383 # blocks of the vectors of N=224 because we don't support it.
384 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200385 for line in vector_data:
386 line = line.strip()
387
388 if not line or line.startswith("#"):
389 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200390 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200391 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200392 elif line.startswith("[mod = L=2048, N=224"):
393 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200394 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200395 elif line.startswith("[mod = L=2048, N=256"):
396 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200397 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200398 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200399 continue
400
Mohammed Attia49b92592014-03-12 20:07:05 +0200401 if not reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200402 continue
403
Mohammed Attia49b92592014-03-12 20:07:05 +0200404 elif reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200405 if line.startswith("P"):
406 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200407 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200408 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200409 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200410 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200411 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200412 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200413 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200414 vectors.append({'p': vectors[-1]['p'],
415 'q': vectors[-1]['q'],
416 'g': vectors[-1]['g'],
417 'x': int(line.split("=")[1], 16)
418 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200419 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200420 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200421
422 return vectors