Debian Codegraph @

lib/Crypto/SelfTest/loader.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2016, Legrandin <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 import os
32 import re
33 import json
34 import errno
35 import binascii
36 import warnings
37 from binascii import unhexlify
38 from Crypto.Util.py3compat import FileNotFoundError
39
40
41 try:
42 import pycryptodome_test_vectors # type: ignore
43 test_vectors_available = True
44 except ImportError:
45 test_vectors_available = False
46
47
48 def _load_tests(dir_comps, file_in, description, conversions):
49 """Load and parse a test vector file
50
51 Return a list of objects, one per group of adjacent
52 KV lines or for a single line in the form "[.*]".
53
54 For a group of lines, the object has one attribute per line.
55 """
56
57 line_number = 0
58 results = []
59
60 class TestVector(object):
61 def __init__(self, description, count):
62 self.desc = description
63 self.count = count
64 self.others = []
65
66 test_vector = None
67 count = 0
68 new_group = True
69
70 while True:
71 line_number += 1
72 line = file_in.readline()
73 if not line:
74 if test_vector is not None:
75 results.append(test_vector)
76 break
77 line = line.strip()
78
79 # Skip comments and empty lines
80 if line.startswith('#') or not line:
81 new_group = True
82 continue
83
84 if line.startswith("["):
85 if test_vector is not None:
86 results.append(test_vector)
87 test_vector = None
88 results.append(line)
89 continue
90
91 if new_group:
92 count += 1
93 new_group = False
94 if test_vector is not None:
95 results.append(test_vector)
96 test_vector = TestVector("%s (#%d)" % (description, count), count)
97
98 res = re.match("([A-Za-z0-9]+) = ?(.*)", line)
99 if not res:
100 test_vector.others += [line]
101 else:
102 token = res.group(1).lower()
103 data = res.group(2).lower()
104
105 conversion = conversions.get(token, None)
106 if conversion is None:
107 if len(data) % 2 != 0:
108 data = "0" + data
109 setattr(test_vector, token, binascii.unhexlify(data))
110 else:
111 setattr(test_vector, token, conversion(data))
112
113 # This line is ignored
114 return results
115
116
117 def load_test_vectors(dir_comps, file_name, description, conversions):
118 """Load and parse a test vector file, formatted using the NIST style.
119
120 Args:
121 dir_comps (list of strings):
122 The path components under the ``pycryptodome_test_vectors`` package.
123 For instance ``("Cipher", "AES")``.
124 file_name (string):
125 The name of the file with the test vectors.
126 description (string):
127 A description applicable to the test vectors in the file.
128 conversions (dictionary):
129 The dictionary contains functions.
130 Values in the file that have an entry in this dictionary
131 will be converted usign the matching function.
132 Otherwise, values will be considered as hexadecimal and
133 converted to binary.
134
135 Returns:
136 A list of test vector objects.
137
138 The file is formatted in the following way:
139
140 - Lines starting with "#" are comments and will be ignored.
141 - Each test vector is a sequence of 1 or more adjacent lines, where
142 each lines is an assignement.
143 - Test vectors are separated by an empty line, a comment, or
144 a line starting with "[".
145
146 A test vector object has the following attributes:
147
148 - desc (string): description
149 - counter (int): the order of the test vector in the file (from 1)
150 - others (list): zero or more lines of the test vector that were not assignments
151 - left-hand side of each assignment (lowercase): the value of the
152 assignement, either converted or bytes.
153 """
154
155 results = None
156
157 try:
158 if not test_vectors_available:
159 raise FileNotFoundError(errno.ENOENT,
160 os.strerror(errno.ENOENT),
161 file_name)
162
163 description = "%s test (%s)" % (description, file_name)
164
165 init_dir = os.path.dirname(pycryptodome_test_vectors.__file__)
166 full_file_name = os.path.join(os.path.join(init_dir, *dir_comps), file_name)
167 with open(full_file_name) as file_in:
168 results = _load_tests(dir_comps, file_in, description, conversions)
169
170 except FileNotFoundError:
171 warnings.warn("Warning: skipping extended tests for " + description,
172 UserWarning,
173 stacklevel=2)
174
175 return results
176
177
178 def load_test_vectors_wycheproof(dir_comps, file_name, description,
179 root_tag={}, group_tag={}, unit_tag={}):
180
181 result = []
182 try:
183 if not test_vectors_available:
184 raise FileNotFoundError(errno.ENOENT,
185 os.strerror(errno.ENOENT),
186 file_name)
187
188 init_dir = os.path.dirname(pycryptodome_test_vectors.__file__)
189 full_file_name = os.path.join(os.path.join(init_dir, *dir_comps), file_name)
190 with open(full_file_name) as file_in:
191 tv_tree = json.load(file_in)
192
193 except FileNotFoundError:
194 warnings.warn("Warning: skipping extended tests for " + description,
195 UserWarning,
196 stacklevel=2)
197 return result
198
199 class TestVector(object):
200 pass
201
202 common_root = {}
203 for k, v in root_tag.items():
204 common_root[k] = v(tv_tree)
205
206 for group in tv_tree['testGroups']:
207
208 common_group = {}
209 for k, v in group_tag.items():
210 common_group[k] = v(group)
211
212 for test in group['tests']:
213 tv = TestVector()
214
215 for k, v in common_root.items():
216 setattr(tv, k, v)
217 for k, v in common_group.items():
218 setattr(tv, k, v)
219
220 tv.id = test['tcId']
221 tv.comment = test['comment']
222 for attr in 'key', 'iv', 'aad', 'msg', 'ct', 'tag', 'label', \
223 'ikm', 'salt', 'info', 'okm', 'sig', 'public', 'shared':
224 if attr in test:
225 setattr(tv, attr, unhexlify(test[attr]))
226 tv.filename = file_name
227
228 for k, v in unit_tag.items():
229 setattr(tv, k, v(test))
230
231 tv.valid = test['result'] != "invalid"
232 tv.warning = test['result'] == "acceptable"
233
234 tv.filename = file_name
235
236 result.append(tv)
237
238 return result
239