loader.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2016, Legrandin <helderijs@gmail.com>
  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. import os
  31. import re
  32. import json
  33. import errno
  34. import binascii
  35. import warnings
  36. from binascii import unhexlify
  37. from Crypto.Util.py3compat import FileNotFoundError
  38. try:
  39. import pycryptodome_test_vectors # type: ignore
  40. test_vectors_available = True
  41. except ImportError:
  42. test_vectors_available = False
  43. def _load_tests(dir_comps, file_in, description, conversions):
  44. """Load and parse a test vector file
  45. Return a list of objects, one per group of adjacent
  46. KV lines or for a single line in the form "[.*]".
  47. For a group of lines, the object has one attribute per line.
  48. """
  49. line_number = 0
  50. results = []
  51. class TestVector(object):
  52. def __init__(self, description, count):
  53. self.desc = description
  54. self.count = count
  55. self.others = []
  56. test_vector = None
  57. count = 0
  58. new_group = True
  59. while True:
  60. line_number += 1
  61. line = file_in.readline()
  62. if not line:
  63. if test_vector is not None:
  64. results.append(test_vector)
  65. break
  66. line = line.strip()
  67. # Skip comments and empty lines
  68. if line.startswith('#') or not line:
  69. new_group = True
  70. continue
  71. if line.startswith("["):
  72. if test_vector is not None:
  73. results.append(test_vector)
  74. test_vector = None
  75. results.append(line)
  76. continue
  77. if new_group:
  78. count += 1
  79. new_group = False
  80. if test_vector is not None:
  81. results.append(test_vector)
  82. test_vector = TestVector("%s (#%d)" % (description, count), count)
  83. res = re.match("([A-Za-z0-9]+) = ?(.*)", line)
  84. if not res:
  85. test_vector.others += [line]
  86. else:
  87. token = res.group(1).lower()
  88. data = res.group(2).lower()
  89. conversion = conversions.get(token, None)
  90. if conversion is None:
  91. if len(data) % 2 != 0:
  92. data = "0" + data
  93. setattr(test_vector, token, binascii.unhexlify(data))
  94. else:
  95. setattr(test_vector, token, conversion(data))
  96. # This line is ignored
  97. return results
  98. def load_test_vectors(dir_comps, file_name, description, conversions):
  99. """Load and parse a test vector file, formatted using the NIST style.
  100. Args:
  101. dir_comps (list of strings):
  102. The path components under the ``pycryptodome_test_vectors`` package.
  103. For instance ``("Cipher", "AES")``.
  104. file_name (string):
  105. The name of the file with the test vectors.
  106. description (string):
  107. A description applicable to the test vectors in the file.
  108. conversions (dictionary):
  109. The dictionary contains functions.
  110. Values in the file that have an entry in this dictionary
  111. will be converted usign the matching function.
  112. Otherwise, values will be considered as hexadecimal and
  113. converted to binary.
  114. Returns:
  115. A list of test vector objects.
  116. The file is formatted in the following way:
  117. - Lines starting with "#" are comments and will be ignored.
  118. - Each test vector is a sequence of 1 or more adjacent lines, where
  119. each lines is an assignement.
  120. - Test vectors are separated by an empty line, a comment, or
  121. a line starting with "[".
  122. A test vector object has the following attributes:
  123. - desc (string): description
  124. - counter (int): the order of the test vector in the file (from 1)
  125. - others (list): zero or more lines of the test vector that were not assignments
  126. - left-hand side of each assignment (lowercase): the value of the
  127. assignement, either converted or bytes.
  128. """
  129. results = None
  130. try:
  131. if not test_vectors_available:
  132. raise FileNotFoundError(errno.ENOENT,
  133. os.strerror(errno.ENOENT),
  134. file_name)
  135. description = "%s test (%s)" % (description, file_name)
  136. init_dir = os.path.dirname(pycryptodome_test_vectors.__file__)
  137. full_file_name = os.path.join(os.path.join(init_dir, *dir_comps), file_name)
  138. with open(full_file_name) as file_in:
  139. results = _load_tests(dir_comps, file_in, description, conversions)
  140. except FileNotFoundError:
  141. warnings.warn("Warning: skipping extended tests for " + description,
  142. UserWarning,
  143. stacklevel=2)
  144. return results
  145. def load_test_vectors_wycheproof(dir_comps, file_name, description,
  146. root_tag={}, group_tag={}, unit_tag={}):
  147. result = []
  148. try:
  149. if not test_vectors_available:
  150. raise FileNotFoundError(errno.ENOENT,
  151. os.strerror(errno.ENOENT),
  152. file_name)
  153. init_dir = os.path.dirname(pycryptodome_test_vectors.__file__)
  154. full_file_name = os.path.join(os.path.join(init_dir, *dir_comps), file_name)
  155. with open(full_file_name) as file_in:
  156. tv_tree = json.load(file_in)
  157. except FileNotFoundError:
  158. warnings.warn("Warning: skipping extended tests for " + description,
  159. UserWarning,
  160. stacklevel=2)
  161. return result
  162. class TestVector(object):
  163. pass
  164. common_root = {}
  165. for k, v in root_tag.items():
  166. common_root[k] = v(tv_tree)
  167. for group in tv_tree['testGroups']:
  168. common_group = {}
  169. for k, v in group_tag.items():
  170. common_group[k] = v(group)
  171. for test in group['tests']:
  172. tv = TestVector()
  173. for k, v in common_root.items():
  174. setattr(tv, k, v)
  175. for k, v in common_group.items():
  176. setattr(tv, k, v)
  177. tv.id = test['tcId']
  178. tv.comment = test['comment']
  179. for attr in 'key', 'iv', 'aad', 'msg', 'ct', 'tag', 'label', \
  180. 'ikm', 'salt', 'info', 'okm', 'sig', 'public', 'shared':
  181. if attr in test:
  182. setattr(tv, attr, unhexlify(test[attr]))
  183. tv.filename = file_name
  184. for k, v in unit_tag.items():
  185. setattr(tv, k, v(test))
  186. tv.valid = test['result'] != "invalid"
  187. tv.warning = test['result'] == "acceptable"
  188. tv.filename = file_name
  189. result.append(tv)
  190. return result