blob: 5262b733e94f0535e6778a275ae1f6fa8387e49a [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 Gaynor36e651c2014-01-27 10:08:35 -080014import collections
Alex Gaynor2b3f9422013-12-24 21:55:24 -080015import os
16
Alex Stapleton58f27ac2014-02-02 19:30:03 +000017import six
Alex Gaynor2b3f9422013-12-24 21:55:24 -080018import pytest
19
20
Alex Gaynor36e651c2014-01-27 10:08:35 -080021HashVector = collections.namedtuple("HashVector", ["message", "digest"])
22KeyedHashVector = collections.namedtuple(
23 "KeyedHashVector", ["message", "digest", "key"]
24)
25
26
Paul Kehrerc421e632014-01-18 09:22:21 -060027def select_backends(names, backend_list):
28 if names is None:
29 return backend_list
30 split_names = [x.strip() for x in names.split(',')]
31 # this must be duplicated and then removed to preserve the metadata
32 # pytest associates. Appending backends to a new list doesn't seem to work
Paul Kehreraed9e172014-01-19 12:09:27 -060033 selected_backends = []
34 for backend in backend_list:
35 if backend.name in split_names:
36 selected_backends.append(backend)
Paul Kehrerc421e632014-01-18 09:22:21 -060037
Paul Kehreraed9e172014-01-19 12:09:27 -060038 if len(selected_backends) > 0:
39 return selected_backends
Paul Kehrerc421e632014-01-18 09:22:21 -060040 else:
41 raise ValueError(
42 "No backend selected. Tried to select: {0}".format(split_names)
43 )
Paul Kehrer34c075e2014-01-13 21:52:08 -050044
45
Alex Gaynor2b3f9422013-12-24 21:55:24 -080046def check_for_iface(name, iface, item):
47 if name in item.keywords and "backend" in item.funcargs:
48 if not isinstance(item.funcargs["backend"], iface):
49 pytest.skip("{0} backend does not support {1}".format(
50 item.funcargs["backend"], name
51 ))
Donald Stufft9e1a48b2013-08-09 00:32:30 -040052
53
Paul Kehrer60fc8da2013-12-26 20:19:34 -060054def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060055 supported = item.keywords.get("supported")
56 if supported and "backend" in item.funcargs:
57 if not supported.kwargs["only_if"](item.funcargs["backend"]):
Paul Kehrerf03334e2014-01-02 23:16:14 -060058 pytest.skip("{0} ({1})".format(
59 supported.kwargs["skip_message"], item.funcargs["backend"]
60 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060061 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060062 raise ValueError("This mark is only available on methods that take a "
63 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060064
65
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060066def load_vectors_from_file(filename, loader):
67 base = os.path.join(
68 os.path.dirname(__file__), "hazmat", "primitives", "vectors",
69 )
70 with open(os.path.join(base, filename), "r") as vector_file:
71 return loader(vector_file)
72
73
Alex Gaynord3ce7032013-11-11 14:46:20 -080074def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060075 test_data = None
76 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040077
78 for line in vector_data:
79 line = line.strip()
80
Paul Kehrer749ac5b2013-11-18 18:12:41 -060081 # Blank lines, comments, and section headers are ignored
82 if not line or line.startswith("#") or (line.startswith("[")
83 and line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080084 continue
85
Paul Kehrera43b6692013-11-12 15:35:49 -060086 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060087 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060088 continue
89
Donald Stufft9e1a48b2013-08-09 00:32:30 -040090 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060091 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040092
Paul Kehrer1050ddf2014-01-27 21:04:03 -060093 # Some tests (PBKDF2) contain \0, which should be interpreted as a
94 # null character rather than literal.
95 value = value.replace("\\0", "\0")
96
Donald Stufft9e1a48b2013-08-09 00:32:30 -040097 # COUNT is a special token that indicates a new block of data
98 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060099 test_data = {}
100 data.append(test_data)
101 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400102 # For all other tokens we simply want the name, value stored in
103 # the dictionary
104 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600105 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400106
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600107 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400108
109
Paul Kehrer1951bf62013-09-15 12:05:43 -0500110def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500111 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500112
113 for line in vector_data:
114 line = line.strip()
115
116 # Blank lines and comments are ignored
117 if not line or line.startswith("#"):
118 continue
119
120 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500121 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500122 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500123 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500124 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500125 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
126 # after a C is found the K+P+C tuple is complete
127 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700128 cryptrec_list.append({
129 "key": key,
130 "plaintext": pt,
131 "ciphertext": ct
132 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400133 else:
134 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500135 return cryptrec_list
136
137
Paul Kehrer69e06522013-10-18 17:28:39 -0500138def load_hash_vectors(vector_data):
139 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500140 key = None
141 msg = None
142 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500143
144 for line in vector_data:
145 line = line.strip()
146
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500147 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500148 continue
149
150 if line.startswith("Len"):
151 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500152 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800153 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500154 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500155 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800156 # In the NIST vectors they have chosen to represent an empty
157 # string as hex 00, which is of course not actually an empty
158 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500159 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
160 elif line.startswith("MD"):
161 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500162 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500163 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800164 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500165 key = None
166 msg = None
167 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500168 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800169 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500170 msg = None
171 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500172 else:
173 raise ValueError("Unknown line in hash vector")
174 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000175
176
177def load_pkcs1_vectors(vector_data):
178 """
179 Loads data out of RSA PKCS #1 vector files.
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000180 """
181 private_key_vector = None
182 public_key_vector = None
183 attr = None
184 key = None
Paul Kehrerefca2802014-02-17 20:55:13 -0600185 example_vector = None
186 examples = []
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000187 vectors = []
188 for line in vector_data:
Paul Kehrer7774a032014-02-17 22:56:55 -0600189 if (
190 line.startswith("# PSS Example") or
191 line.startswith("# PKCS#1 v1.5 Signature")
192 ):
Paul Kehrerefca2802014-02-17 20:55:13 -0600193 if example_vector:
194 for key, value in six.iteritems(example_vector):
195 hex_str = "".join(value).replace(" ", "")
196 example_vector[key] = hex_str
197 examples.append(example_vector)
198
199 attr = None
200 example_vector = collections.defaultdict(list)
201
202 if line.startswith("# Message to be signed"):
203 attr = "msg"
204 continue
205 elif line.startswith("# Salt"):
206 attr = "salt"
207 continue
208 elif line.startswith("# Signature"):
209 attr = "signature"
210 continue
211 elif (
212 example_vector and
213 line.startswith("# =============================================")
214 ):
215 for key, value in six.iteritems(example_vector):
216 hex_str = "".join(value).replace(" ", "")
217 example_vector[key] = hex_str
218 examples.append(example_vector)
219 example_vector = None
220 attr = None
221 elif example_vector and line.startswith("#"):
222 continue
223 else:
224 if attr is not None and example_vector is not None:
225 example_vector[attr].append(line.strip())
226 continue
227
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000228 if (
229 line.startswith("# Example") or
230 line.startswith("# =============================================")
231 ):
232 if key:
233 assert private_key_vector
234 assert public_key_vector
235
236 for key, value in six.iteritems(public_key_vector):
237 hex_str = "".join(value).replace(" ", "")
238 public_key_vector[key] = int(hex_str, 16)
239
240 for key, value in six.iteritems(private_key_vector):
241 hex_str = "".join(value).replace(" ", "")
242 private_key_vector[key] = int(hex_str, 16)
243
Paul Kehrerefca2802014-02-17 20:55:13 -0600244 private_key_vector["examples"] = examples
245 examples = []
246
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000247 assert (
248 private_key_vector['public_exponent'] ==
249 public_key_vector['public_exponent']
250 )
251
252 assert (
253 private_key_vector['modulus'] ==
254 public_key_vector['modulus']
255 )
256
257 vectors.append(
258 (private_key_vector, public_key_vector)
259 )
260
261 public_key_vector = collections.defaultdict(list)
262 private_key_vector = collections.defaultdict(list)
263 key = None
264 attr = None
265
266 if private_key_vector is None or public_key_vector is None:
267 continue
268
269 if line.startswith("# Private key"):
270 key = private_key_vector
271 elif line.startswith("# Public key"):
272 key = public_key_vector
273 elif line.startswith("# Modulus:"):
274 attr = "modulus"
275 elif line.startswith("# Public exponent:"):
276 attr = "public_exponent"
277 elif line.startswith("# Exponent:"):
278 if key is public_key_vector:
279 attr = "public_exponent"
280 else:
281 assert key is private_key_vector
282 attr = "private_exponent"
283 elif line.startswith("# Prime 1:"):
284 attr = "p"
285 elif line.startswith("# Prime 2:"):
286 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600287 elif line.startswith("# Prime exponent 1:"):
288 attr = "dmp1"
289 elif line.startswith("# Prime exponent 2:"):
290 attr = "dmq1"
291 elif line.startswith("# Coefficient:"):
292 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000293 elif line.startswith("#"):
294 attr = None
295 else:
296 if key is not None and attr is not None:
297 key[attr].append(line.strip())
298 return vectors