blob: 3e35970ebbf752c12ec2c0163906105e42ae05ac [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
Paul Kehrer90450f32014-03-19 12:37:17 -040017
Alex Stapletona39a3192014-03-14 20:03:12 +000018import pytest
19
Paul Kehrerafc1ccd2014-03-19 11:49:32 -040020import six
Alex Gaynor2b3f9422013-12-24 21:55:24 -080021
Alex Stapletona39a3192014-03-14 20:03:12 +000022import cryptography_vectors
Matthew Iversen68e77c72014-03-13 08:54:43 +110023
Alex Gaynor2b3f9422013-12-24 21:55:24 -080024
Alex Gaynor36e651c2014-01-27 10:08:35 -080025HashVector = collections.namedtuple("HashVector", ["message", "digest"])
26KeyedHashVector = collections.namedtuple(
27 "KeyedHashVector", ["message", "digest", "key"]
28)
29
30
Paul Kehrerc421e632014-01-18 09:22:21 -060031def select_backends(names, backend_list):
32 if names is None:
33 return backend_list
34 split_names = [x.strip() for x in names.split(',')]
35 # this must be duplicated and then removed to preserve the metadata
36 # pytest associates. Appending backends to a new list doesn't seem to work
Paul Kehreraed9e172014-01-19 12:09:27 -060037 selected_backends = []
38 for backend in backend_list:
39 if backend.name in split_names:
40 selected_backends.append(backend)
Paul Kehrerc421e632014-01-18 09:22:21 -060041
Paul Kehreraed9e172014-01-19 12:09:27 -060042 if len(selected_backends) > 0:
43 return selected_backends
Paul Kehrerc421e632014-01-18 09:22:21 -060044 else:
45 raise ValueError(
46 "No backend selected. Tried to select: {0}".format(split_names)
47 )
Paul Kehrer34c075e2014-01-13 21:52:08 -050048
49
Alex Gaynor2b3f9422013-12-24 21:55:24 -080050def check_for_iface(name, iface, item):
51 if name in item.keywords and "backend" in item.funcargs:
52 if not isinstance(item.funcargs["backend"], iface):
53 pytest.skip("{0} backend does not support {1}".format(
54 item.funcargs["backend"], name
55 ))
Donald Stufft9e1a48b2013-08-09 00:32:30 -040056
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
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060070def load_vectors_from_file(filename, loader):
Alex Stapletona39a3192014-03-14 20:03:12 +000071 with cryptography_vectors.open_vector_file(filename) as vector_file:
72 return loader(vector_file)
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060073
74
Alex Gaynord3ce7032013-11-11 14:46:20 -080075def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060076 test_data = None
77 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040078
79 for line in vector_data:
80 line = line.strip()
81
Paul Kehrer749ac5b2013-11-18 18:12:41 -060082 # Blank lines, comments, and section headers are ignored
83 if not line or line.startswith("#") or (line.startswith("[")
84 and line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080085 continue
86
Paul Kehrera43b6692013-11-12 15:35:49 -060087 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060088 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060089 continue
90
Donald Stufft9e1a48b2013-08-09 00:32:30 -040091 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060092 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040093
Paul Kehrer1050ddf2014-01-27 21:04:03 -060094 # Some tests (PBKDF2) contain \0, which should be interpreted as a
95 # null character rather than literal.
96 value = value.replace("\\0", "\0")
97
Donald Stufft9e1a48b2013-08-09 00:32:30 -040098 # COUNT is a special token that indicates a new block of data
99 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600100 test_data = {}
101 data.append(test_data)
102 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400103 # For all other tokens we simply want the name, value stored in
104 # the dictionary
105 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600106 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400107
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600108 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400109
110
Paul Kehrer1951bf62013-09-15 12:05:43 -0500111def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500112 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500113
114 for line in vector_data:
115 line = line.strip()
116
117 # Blank lines and comments are ignored
118 if not line or line.startswith("#"):
119 continue
120
121 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500122 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500123 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500124 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500125 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500126 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
127 # after a C is found the K+P+C tuple is complete
128 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700129 cryptrec_list.append({
130 "key": key,
131 "plaintext": pt,
132 "ciphertext": ct
133 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400134 else:
135 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500136 return cryptrec_list
137
138
Paul Kehrer69e06522013-10-18 17:28:39 -0500139def load_hash_vectors(vector_data):
140 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500141 key = None
142 msg = None
143 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500144
145 for line in vector_data:
146 line = line.strip()
147
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500148 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500149 continue
150
151 if line.startswith("Len"):
152 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500153 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800154 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500155 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500156 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800157 # In the NIST vectors they have chosen to represent an empty
158 # string as hex 00, which is of course not actually an empty
159 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500160 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
161 elif line.startswith("MD"):
162 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500163 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500164 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800165 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500166 key = None
167 msg = None
168 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500169 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800170 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500171 msg = None
172 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500173 else:
174 raise ValueError("Unknown line in hash vector")
175 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000176
177
178def load_pkcs1_vectors(vector_data):
179 """
180 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000181 """
182 private_key_vector = None
183 public_key_vector = None
184 attr = None
185 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600186 example_vector = None
187 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000188 vectors = []
189 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600190 if (
191 line.startswith("# PSS Example") or
192 line.startswith("# PKCS#1 v1.5 Signature")
193 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600194 if example_vector:
195 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600196 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600197 example_vector[key] = hex_str
198 examples.append(example_vector)
199
200 attr = None
201 example_vector = collections.defaultdict(list)
202
203 if line.startswith("# Message to be signed"):
Paul Kehrer7d9c3062014-02-18 08:27:39 -0600204 attr = "message"
Paul Kehrerefca2802014-02-17 20:55:13 -0600205 continue
206 elif line.startswith("# Salt"):
207 attr = "salt"
208 continue
209 elif line.startswith("# Signature"):
210 attr = "signature"
211 continue
212 elif (
213 example_vector and
214 line.startswith("# =============================================")
215 ):
216 for key, value in six.iteritems(example_vector):
Paul Kehrer26811802014-02-19 16:32:11 -0600217 hex_str = "".join(value).replace(" ", "").encode("ascii")
Paul Kehrerefca2802014-02-17 20:55:13 -0600218 example_vector[key] = hex_str
219 examples.append(example_vector)
220 example_vector = None
221 attr = None
222 elif example_vector and line.startswith("#"):
223 continue
224 else:
225 if attr is not None and example_vector is not None:
226 example_vector[attr].append(line.strip())
227 continue
228
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000229 if (
230 line.startswith("# Example") or
231 line.startswith("# =============================================")
232 ):
233 if key:
234 assert private_key_vector
235 assert public_key_vector
236
237 for key, value in six.iteritems(public_key_vector):
238 hex_str = "".join(value).replace(" ", "")
239 public_key_vector[key] = int(hex_str, 16)
240
241 for key, value in six.iteritems(private_key_vector):
242 hex_str = "".join(value).replace(" ", "")
243 private_key_vector[key] = int(hex_str, 16)
244
Paul Kehrerefca2802014-02-17 20:55:13 -0600245 private_key_vector["examples"] = examples
246 examples = []
247
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000248 assert (
249 private_key_vector['public_exponent'] ==
250 public_key_vector['public_exponent']
251 )
252
253 assert (
254 private_key_vector['modulus'] ==
255 public_key_vector['modulus']
256 )
257
258 vectors.append(
259 (private_key_vector, public_key_vector)
260 )
261
262 public_key_vector = collections.defaultdict(list)
263 private_key_vector = collections.defaultdict(list)
264 key = None
265 attr = None
266
267 if private_key_vector is None or public_key_vector is None:
268 continue
269
270 if line.startswith("# Private key"):
271 key = private_key_vector
272 elif line.startswith("# Public key"):
273 key = public_key_vector
274 elif line.startswith("# Modulus:"):
275 attr = "modulus"
276 elif line.startswith("# Public exponent:"):
277 attr = "public_exponent"
278 elif line.startswith("# Exponent:"):
279 if key is public_key_vector:
280 attr = "public_exponent"
281 else:
282 assert key is private_key_vector
283 attr = "private_exponent"
284 elif line.startswith("# Prime 1:"):
285 attr = "p"
286 elif line.startswith("# Prime 2:"):
287 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600288 elif line.startswith("# Prime exponent 1:"):
289 attr = "dmp1"
290 elif line.startswith("# Prime exponent 2:"):
291 attr = "dmq1"
292 elif line.startswith("# Coefficient:"):
293 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000294 elif line.startswith("#"):
295 attr = None
296 else:
297 if key is not None and attr is not None:
298 key[attr].append(line.strip())
299 return vectors
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400300
301
302def load_rsa_nist_vectors(vector_data):
303 test_data = None
Paul Kehrer62707f12014-03-18 07:19:14 -0400304 p = None
Paul Kehrerafc25182014-03-18 07:51:56 -0400305 salt_length = None
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400306 data = []
307
308 for line in vector_data:
309 line = line.strip()
310
311 # Blank lines and section headers are ignored
312 if not line or line.startswith("["):
313 continue
314
315 if line.startswith("# Salt len:"):
316 salt_length = int(line.split(":")[1].strip())
317 continue
318 elif line.startswith("#"):
319 continue
320
321 # Build our data using a simple Key = Value format
322 name, value = [c.strip() for c in line.split("=")]
323
324 if name == "n":
325 n = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400326 elif name == "e" and p is None:
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400327 e = int(value, 16)
Paul Kehrer62707f12014-03-18 07:19:14 -0400328 elif name == "p":
329 p = int(value, 16)
330 elif name == "q":
331 q = int(value, 16)
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400332 elif name == "SHAAlg":
Paul Kehrer62707f12014-03-18 07:19:14 -0400333 if p is None:
334 test_data = {
335 "modulus": n,
336 "public_exponent": e,
337 "salt_length": salt_length,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400338 "algorithm": value,
Paul Kehrer62707f12014-03-18 07:19:14 -0400339 "fail": False
340 }
341 else:
342 test_data = {
343 "modulus": n,
344 "p": p,
345 "q": q,
Paul Kehrere66f69a2014-03-18 07:57:26 -0400346 "algorithm": value
Paul Kehrer62707f12014-03-18 07:19:14 -0400347 }
Paul Kehrerafc25182014-03-18 07:51:56 -0400348 if salt_length is not None:
349 test_data["salt_length"] = salt_length
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400350 data.append(test_data)
Paul Kehrer62707f12014-03-18 07:19:14 -0400351 elif name == "e" and p is not None:
352 test_data["public_exponent"] = int(value, 16)
353 elif name == "d":
354 test_data["private_exponent"] = int(value, 16)
355 elif name == "Result":
356 test_data["fail"] = value.startswith("F")
Paul Kehrer2f2a2062014-03-10 23:30:28 -0400357 # For all other tokens we simply want the name, value stored in
358 # the dictionary
359 else:
360 test_data[name.lower()] = value.encode("ascii")
361
362 return data
Mohammed Attia987cc702014-03-12 16:07:21 +0200363
364
365def load_fips_dsa_key_pair_vectors(vector_data):
366 """
367 Loads data out of the FIPS DSA KeyPair vector files.
368 """
369 vectors = []
Mohammed Attia49b92592014-03-12 20:07:05 +0200370 # When reading_key_data is set to True it tells the loader to continue
371 # constructing dictionaries. We set reading_key_data to False during the
372 # blocks of the vectors of N=224 because we don't support it.
373 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200374 for line in vector_data:
375 line = line.strip()
376
377 if not line or line.startswith("#"):
378 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200379 elif line.startswith("[mod = L=1024"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200380 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200381 elif line.startswith("[mod = L=2048, N=224"):
382 reading_key_data = False
Mohammed Attia987cc702014-03-12 16:07:21 +0200383 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200384 elif line.startswith("[mod = L=2048, N=256"):
385 reading_key_data = True
Mohammed Attia987cc702014-03-12 16:07:21 +0200386 continue
Mohammed Attia49b92592014-03-12 20:07:05 +0200387 elif line.startswith("[mod = L=3072"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200388 continue
389
Mohammed Attia49b92592014-03-12 20:07:05 +0200390 if not reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200391 continue
392
Mohammed Attia49b92592014-03-12 20:07:05 +0200393 elif reading_key_data:
Mohammed Attia987cc702014-03-12 16:07:21 +0200394 if line.startswith("P"):
395 vectors.append({'p': int(line.split("=")[1], 16)})
Mohammed Attia22ccb872014-03-12 18:27:59 +0200396 elif line.startswith("Q"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200397 vectors[-1]['q'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200398 elif line.startswith("G"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200399 vectors[-1]['g'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200400 elif line.startswith("X") and 'x' not in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200401 vectors[-1]['x'] = int(line.split("=")[1], 16)
Mohammed Attia22ccb872014-03-12 18:27:59 +0200402 elif line.startswith("X") and 'x' in vectors[-1]:
Mohammed Attia987cc702014-03-12 16:07:21 +0200403 vectors.append({'p': vectors[-1]['p'],
404 'q': vectors[-1]['q'],
405 'g': vectors[-1]['g'],
406 'x': int(line.split("=")[1], 16)
407 })
Mohammed Attia22ccb872014-03-12 18:27:59 +0200408 elif line.startswith("Y"):
Mohammed Attia987cc702014-03-12 16:07:21 +0200409 vectors[-1]['y'] = int(line.split("=")[1], 16)
Mohammed Attia987cc702014-03-12 16:07:21 +0200410
411 return vectors