blob: 3c150a2ee25b50a284d1979893115f182f4fb308 [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.
180
181 Currently only returns the key pairs.
182 """
183 private_key_vector = None
184 public_key_vector = None
185 attr = None
186 key = None
187 vectors = []
188 for line in vector_data:
189 if (
190 line.startswith("# Example") or
191 line.startswith("# =============================================")
192 ):
193 if key:
194 assert private_key_vector
195 assert public_key_vector
196
197 for key, value in six.iteritems(public_key_vector):
198 hex_str = "".join(value).replace(" ", "")
199 public_key_vector[key] = int(hex_str, 16)
200
201 for key, value in six.iteritems(private_key_vector):
202 hex_str = "".join(value).replace(" ", "")
203 private_key_vector[key] = int(hex_str, 16)
204
205 assert (
206 private_key_vector['public_exponent'] ==
207 public_key_vector['public_exponent']
208 )
209
210 assert (
211 private_key_vector['modulus'] ==
212 public_key_vector['modulus']
213 )
214
215 vectors.append(
216 (private_key_vector, public_key_vector)
217 )
218
219 public_key_vector = collections.defaultdict(list)
220 private_key_vector = collections.defaultdict(list)
221 key = None
222 attr = None
223
224 if private_key_vector is None or public_key_vector is None:
225 continue
226
227 if line.startswith("# Private key"):
228 key = private_key_vector
229 elif line.startswith("# Public key"):
230 key = public_key_vector
231 elif line.startswith("# Modulus:"):
232 attr = "modulus"
233 elif line.startswith("# Public exponent:"):
234 attr = "public_exponent"
235 elif line.startswith("# Exponent:"):
236 if key is public_key_vector:
237 attr = "public_exponent"
238 else:
239 assert key is private_key_vector
240 attr = "private_exponent"
241 elif line.startswith("# Prime 1:"):
242 attr = "p"
243 elif line.startswith("# Prime 2:"):
244 attr = "q"
Paul Kehrer09328bb2014-02-12 23:57:27 -0600245 elif line.startswith("# Prime exponent 1:"):
246 attr = "dmp1"
247 elif line.startswith("# Prime exponent 2:"):
248 attr = "dmq1"
249 elif line.startswith("# Coefficient:"):
250 attr = "iqmp"
Alex Stapleton58f27ac2014-02-02 19:30:03 +0000251 elif line.startswith("#"):
252 attr = None
253 else:
254 if key is not None and attr is not None:
255 key[attr].append(line.strip())
256 return vectors