blob: 507bc421be9029c1bb15a240b7cf8cdfdf5bdc1a [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
17import pytest
18
19
Alex Gaynor36e651c2014-01-27 10:08:35 -080020HashVector = collections.namedtuple("HashVector", ["message", "digest"])
21KeyedHashVector = collections.namedtuple(
22 "KeyedHashVector", ["message", "digest", "key"]
23)
24
25
Paul Kehrerc421e632014-01-18 09:22:21 -060026def select_backends(names, backend_list):
27 if names is None:
28 return backend_list
29 split_names = [x.strip() for x in names.split(',')]
30 # this must be duplicated and then removed to preserve the metadata
31 # pytest associates. Appending backends to a new list doesn't seem to work
Paul Kehreraed9e172014-01-19 12:09:27 -060032 selected_backends = []
33 for backend in backend_list:
34 if backend.name in split_names:
35 selected_backends.append(backend)
Paul Kehrerc421e632014-01-18 09:22:21 -060036
Paul Kehreraed9e172014-01-19 12:09:27 -060037 if len(selected_backends) > 0:
38 return selected_backends
Paul Kehrerc421e632014-01-18 09:22:21 -060039 else:
40 raise ValueError(
41 "No backend selected. Tried to select: {0}".format(split_names)
42 )
Paul Kehrer34c075e2014-01-13 21:52:08 -050043
44
Alex Gaynor2b3f9422013-12-24 21:55:24 -080045def check_for_iface(name, iface, item):
46 if name in item.keywords and "backend" in item.funcargs:
47 if not isinstance(item.funcargs["backend"], iface):
48 pytest.skip("{0} backend does not support {1}".format(
49 item.funcargs["backend"], name
50 ))
Donald Stufft9e1a48b2013-08-09 00:32:30 -040051
52
Paul Kehrer60fc8da2013-12-26 20:19:34 -060053def check_backend_support(item):
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060054 supported = item.keywords.get("supported")
55 if supported and "backend" in item.funcargs:
56 if not supported.kwargs["only_if"](item.funcargs["backend"]):
Paul Kehrerf03334e2014-01-02 23:16:14 -060057 pytest.skip("{0} ({1})".format(
58 supported.kwargs["skip_message"], item.funcargs["backend"]
59 ))
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060060 elif supported:
Paul Kehrerec495502013-12-27 15:51:40 -060061 raise ValueError("This mark is only available on methods that take a "
62 "backend")
Paul Kehrer5a8fdf82013-12-26 20:13:45 -060063
64
Paul Kehrerf7f6a9f2013-11-11 20:43:52 -060065def load_vectors_from_file(filename, loader):
66 base = os.path.join(
67 os.path.dirname(__file__), "hazmat", "primitives", "vectors",
68 )
69 with open(os.path.join(base, filename), "r") as vector_file:
70 return loader(vector_file)
71
72
Alex Gaynord3ce7032013-11-11 14:46:20 -080073def load_nist_vectors(vector_data):
Paul Kehrer749ac5b2013-11-18 18:12:41 -060074 test_data = None
75 data = []
Donald Stufft9e1a48b2013-08-09 00:32:30 -040076
77 for line in vector_data:
78 line = line.strip()
79
Paul Kehrer749ac5b2013-11-18 18:12:41 -060080 # Blank lines, comments, and section headers are ignored
81 if not line or line.startswith("#") or (line.startswith("[")
82 and line.endswith("]")):
Alex Gaynor521c42d2013-11-11 14:25:59 -080083 continue
84
Paul Kehrera43b6692013-11-12 15:35:49 -060085 if line.strip() == "FAIL":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060086 test_data["fail"] = True
Paul Kehrera43b6692013-11-12 15:35:49 -060087 continue
88
Donald Stufft9e1a48b2013-08-09 00:32:30 -040089 # Build our data using a simple Key = Value format
Paul Kehrera43b6692013-11-12 15:35:49 -060090 name, value = [c.strip() for c in line.split("=")]
Donald Stufft9e1a48b2013-08-09 00:32:30 -040091
92 # COUNT is a special token that indicates a new block of data
93 if name.upper() == "COUNT":
Paul Kehrer749ac5b2013-11-18 18:12:41 -060094 test_data = {}
95 data.append(test_data)
96 continue
Donald Stufft9e1a48b2013-08-09 00:32:30 -040097 # For all other tokens we simply want the name, value stored in
98 # the dictionary
99 else:
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600100 test_data[name.lower()] = value.encode("ascii")
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400101
Paul Kehrer749ac5b2013-11-18 18:12:41 -0600102 return data
Donald Stufft9e1a48b2013-08-09 00:32:30 -0400103
104
Paul Kehrer1951bf62013-09-15 12:05:43 -0500105def load_cryptrec_vectors(vector_data):
Paul Kehrere5805982013-09-27 11:26:01 -0500106 cryptrec_list = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500107
108 for line in vector_data:
109 line = line.strip()
110
111 # Blank lines and comments are ignored
112 if not line or line.startswith("#"):
113 continue
114
115 if line.startswith("K"):
Paul Kehrere5805982013-09-27 11:26:01 -0500116 key = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500117 elif line.startswith("P"):
Paul Kehrere5805982013-09-27 11:26:01 -0500118 pt = line.split(" : ")[1].replace(" ", "").encode("ascii")
Paul Kehrer1951bf62013-09-15 12:05:43 -0500119 elif line.startswith("C"):
Paul Kehrere5805982013-09-27 11:26:01 -0500120 ct = line.split(" : ")[1].replace(" ", "").encode("ascii")
121 # after a C is found the K+P+C tuple is complete
122 # there are many P+C pairs for each K
Alex Gaynor1fe70b12013-10-16 11:59:17 -0700123 cryptrec_list.append({
124 "key": key,
125 "plaintext": pt,
126 "ciphertext": ct
127 })
Donald Stufft3359d7e2013-10-19 19:33:06 -0400128 else:
129 raise ValueError("Invalid line in file '{}'".format(line))
Paul Kehrer1951bf62013-09-15 12:05:43 -0500130 return cryptrec_list
131
132
Paul Kehrer6b99a1b2013-09-24 16:50:21 -0500133def load_openssl_vectors(vector_data):
134 vectors = []
Paul Kehrer1951bf62013-09-15 12:05:43 -0500135
136 for line in vector_data:
137 line = line.strip()
138
139 # Blank lines and comments are ignored
140 if not line or line.startswith("#"):
141 continue
142
143 vector = line.split(":")
Alex Gaynor016eed12013-10-16 14:16:04 -0700144 vectors.append({
145 "key": vector[1].encode("ascii"),
146 "iv": vector[2].encode("ascii"),
147 "plaintext": vector[3].encode("ascii"),
148 "ciphertext": vector[4].encode("ascii"),
149 })
Paul Kehrer6b99a1b2013-09-24 16:50:21 -0500150 return vectors
Paul Kehrer69e06522013-10-18 17:28:39 -0500151
152
153def load_hash_vectors(vector_data):
154 vectors = []
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500155 key = None
156 msg = None
157 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500158
159 for line in vector_data:
160 line = line.strip()
161
Paul Kehrer87cd0db2013-10-18 18:01:26 -0500162 if not line or line.startswith("#") or line.startswith("["):
Paul Kehrer69e06522013-10-18 17:28:39 -0500163 continue
164
165 if line.startswith("Len"):
166 length = int(line.split(" = ")[1])
Paul Kehrer0317b042013-10-28 17:34:27 -0500167 elif line.startswith("Key"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800168 # HMAC vectors contain a key attribute. Hash vectors do not.
Paul Kehrer0317b042013-10-28 17:34:27 -0500169 key = line.split(" = ")[1].encode("ascii")
Paul Kehrer69e06522013-10-18 17:28:39 -0500170 elif line.startswith("Msg"):
Alex Gaynor36e651c2014-01-27 10:08:35 -0800171 # In the NIST vectors they have chosen to represent an empty
172 # string as hex 00, which is of course not actually an empty
173 # string. So we parse the provided length and catch this edge case.
Paul Kehrer69e06522013-10-18 17:28:39 -0500174 msg = line.split(" = ")[1].encode("ascii") if length > 0 else b""
175 elif line.startswith("MD"):
176 md = line.split(" = ")[1]
Paul Kehrer0317b042013-10-28 17:34:27 -0500177 # after MD is found the Msg+MD (+ potential key) tuple is complete
Paul Kehrer00dd5092013-10-23 09:41:49 -0500178 if key is not None:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800179 vectors.append(KeyedHashVector(msg, md, key))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500180 key = None
181 msg = None
182 md = None
Paul Kehrer00dd5092013-10-23 09:41:49 -0500183 else:
Alex Gaynor36e651c2014-01-27 10:08:35 -0800184 vectors.append(HashVector(msg, md))
Paul Kehrer1bb8b712013-10-27 17:00:14 -0500185 msg = None
186 md = None
Paul Kehrer69e06522013-10-18 17:28:39 -0500187 else:
188 raise ValueError("Unknown line in hash vector")
189 return vectors