blob: 408b05f684ecfd7146b456e0a3f7bf9b7ac2fe4f [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 Kehrer6b99a1b2013-09-24 16:50:21 -0500138def load_openssl_vectors(vector_data):
139 vectors = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500140
141 for line in vector_data:
142 line = line.strip()
143
144 # Blank lines and comments are ignored
145 if not line or line.startswith("#"):
146 continue
147
148 vector = line.split(":")
Alex Gaynor016eed12013-10-16 14:16:04 -0700149 vectors.append({
150 "key": vector[1].encode("ascii"),
151 "iv": vector[2].encode("ascii"),
152 "plaintext": vector[3].encode("ascii"),
153 "ciphertext": vector[4].encode("ascii"),
154 })
Paul Kehrer6b99a1b2013-09-24 16:50:21 -0500155 return vectors
Paul Kehrer69e06522013-10-18 17:28:39 -0500156
157
158def load_hash_vectors(vector_data):
159 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500160 key = None
161 msg = None
162 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500163
164 for line in vector_data:
165 line = line.strip()
166
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500167 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500168 continue
169
170 if line.startswith("Len"):
171 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500172 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800173 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500174 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500175 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800176 # In the NIST vectors they have chosen to represent an empty
177 # string as hex 00, which is of course not actually an empty
178 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500179 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
180 elif line.startswith("MD"):
181 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500182 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500183 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800184 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500185 key = None
186 msg = None
187 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500188 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800189 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500190 msg = None
191 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500192 else:
193 raise ValueError("Unknown line in hash vector")
194 return vectors
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000195
196
197def load_pkcs1_vectors(vector_data):
198 """
199 Loads data out of RSA PKCS #1 vector files.
200
201 Currently only returns the key pairs.
202 """
203 private_key_vector = None
204 public_key_vector = None
205 attr = None
206 key = None
207 vectors = []
208 for line in vector_data:
209 if (
210 line.startswith("# Example") or
211 line.startswith("# =============================================")
212 ):
213 if key:
214 assert private_key_vector
215 assert public_key_vector
216
217 for key, value in six.iteritems(public_key_vector):
218 hex_str = "".join(value).replace(" ", "")
219 public_key_vector[key] = int(hex_str, 16)
220
221 for key, value in six.iteritems(private_key_vector):
222 hex_str = "".join(value).replace(" ", "")
223 private_key_vector[key] = int(hex_str, 16)
224
225 assert (
226 private_key_vector['public_exponent'] ==
227 public_key_vector['public_exponent']
228 )
229
230 assert (
231 private_key_vector['modulus'] ==
232 public_key_vector['modulus']
233 )
234
235 vectors.append(
236 (private_key_vector, public_key_vector)
237 )
238
239 public_key_vector = collections.defaultdict(list)
240 private_key_vector = collections.defaultdict(list)
241 key = None
242 attr = None
243
244 if private_key_vector is None or public_key_vector is None:
245 continue
246
247 if line.startswith("# Private key"):
248 key = private_key_vector
249 elif line.startswith("# Public key"):
250 key = public_key_vector
251 elif line.startswith("# Modulus:"):
252 attr = "modulus"
253 elif line.startswith("# Public exponent:"):
254 attr = "public_exponent"
255 elif line.startswith("# Exponent:"):
256 if key is public_key_vector:
257 attr = "public_exponent"
258 else:
259 assert key is private_key_vector
260 attr = "private_exponent"
261 elif line.startswith("# Prime 1:"):
262 attr = "p"
263 elif line.startswith("# Prime 2:"):
264 attr = "q"
265 elif line.startswith("#"):
266 attr = None
267 else:
268 if key is not None and attr is not None:
269 key[attr].append(line.strip())
270 return vectors