PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/Windows/Python3.8/WPy64-3830/WPy64-3830/python-3.8.3.amd64/Lib/site-packages/Crypto/SelfTest/Hash/test_BLAKE2.py

https://gitlab.com/abhi1tb/build
Python | 443 lines | 322 code | 69 blank | 52 comment | 21 complexity | c045d9d7c83b9c3cb167a5fcd1e7a20a MD5 | raw file
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, 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 re
  31. import unittest
  32. from binascii import unhexlify, hexlify
  33. from Crypto.Util.py3compat import tobytes
  34. from Crypto.Util.strxor import strxor_c
  35. from Crypto.Util._file_system import pycryptodome_filename
  36. from Crypto.SelfTest.st_common import list_test_cases
  37. from Crypto.Hash import BLAKE2b, BLAKE2s
  38. class Blake2Test(unittest.TestCase):
  39. def test_new_positive(self):
  40. h = self.BLAKE2.new(digest_bits=self.max_bits)
  41. for new_func in self.BLAKE2.new, h.new:
  42. for dbits in range(8, self.max_bits + 1, 8):
  43. hobj = new_func(digest_bits=dbits)
  44. self.assertEqual(hobj.digest_size, dbits // 8)
  45. for dbytes in range(1, self.max_bytes + 1):
  46. hobj = new_func(digest_bytes=dbytes)
  47. self.assertEqual(hobj.digest_size, dbytes)
  48. digest1 = new_func(data=b"\x90", digest_bytes=self.max_bytes).digest()
  49. digest2 = new_func(digest_bytes=self.max_bytes).update(b"\x90").digest()
  50. self.assertEqual(digest1, digest2)
  51. new_func(data=b"A", key=b"5", digest_bytes=self.max_bytes)
  52. hobj = h.new()
  53. self.assertEqual(hobj.digest_size, self.max_bytes)
  54. def test_new_negative(self):
  55. h = self.BLAKE2.new(digest_bits=self.max_bits)
  56. for new_func in self.BLAKE2.new, h.new:
  57. self.assertRaises(TypeError, new_func,
  58. digest_bytes=self.max_bytes,
  59. digest_bits=self.max_bits)
  60. self.assertRaises(ValueError, new_func, digest_bytes=0)
  61. self.assertRaises(ValueError, new_func,
  62. digest_bytes=self.max_bytes + 1)
  63. self.assertRaises(ValueError, new_func, digest_bits=7)
  64. self.assertRaises(ValueError, new_func, digest_bits=15)
  65. self.assertRaises(ValueError, new_func,
  66. digest_bits=self.max_bits + 1)
  67. self.assertRaises(TypeError, new_func,
  68. digest_bytes=self.max_bytes,
  69. key=u"string")
  70. self.assertRaises(TypeError, new_func,
  71. digest_bytes=self.max_bytes,
  72. data=u"string")
  73. def test_default_digest_size(self):
  74. digest = self.BLAKE2.new(data=b'abc').digest()
  75. self.assertEquals(len(digest), self.max_bytes)
  76. def test_update(self):
  77. pieces = [b"\x0A" * 200, b"\x14" * 300]
  78. h = self.BLAKE2.new(digest_bytes=self.max_bytes)
  79. h.update(pieces[0]).update(pieces[1])
  80. digest = h.digest()
  81. h = self.BLAKE2.new(digest_bytes=self.max_bytes)
  82. h.update(pieces[0] + pieces[1])
  83. self.assertEqual(h.digest(), digest)
  84. def test_update_negative(self):
  85. h = self.BLAKE2.new(digest_bytes=self.max_bytes)
  86. self.assertRaises(TypeError, h.update, u"string")
  87. def test_digest(self):
  88. h = self.BLAKE2.new(digest_bytes=self.max_bytes)
  89. digest = h.digest()
  90. # hexdigest does not change the state
  91. self.assertEqual(h.digest(), digest)
  92. # digest returns a byte string
  93. self.failUnless(isinstance(digest, type(b"digest")))
  94. def test_update_after_digest(self):
  95. msg=b"rrrrttt"
  96. # Normally, update() cannot be done after digest()
  97. h = self.BLAKE2.new(digest_bits=256, data=msg[:4])
  98. dig1 = h.digest()
  99. self.assertRaises(TypeError, h.update, msg[4:])
  100. dig2 = self.BLAKE2.new(digest_bits=256, data=msg).digest()
  101. # With the proper flag, it is allowed
  102. h = self.BLAKE2.new(digest_bits=256, data=msg[:4], update_after_digest=True)
  103. self.assertEquals(h.digest(), dig1)
  104. # ... and the subsequent digest applies to the entire message
  105. # up to that point
  106. h.update(msg[4:])
  107. self.assertEquals(h.digest(), dig2)
  108. def test_hex_digest(self):
  109. mac = self.BLAKE2.new(digest_bits=self.max_bits)
  110. digest = mac.digest()
  111. hexdigest = mac.hexdigest()
  112. # hexdigest is equivalent to digest
  113. self.assertEqual(hexlify(digest), tobytes(hexdigest))
  114. # hexdigest does not change the state
  115. self.assertEqual(mac.hexdigest(), hexdigest)
  116. # hexdigest returns a string
  117. self.failUnless(isinstance(hexdigest, type("digest")))
  118. def test_verify(self):
  119. h = self.BLAKE2.new(digest_bytes=self.max_bytes, key=b"4")
  120. mac = h.digest()
  121. h.verify(mac)
  122. wrong_mac = strxor_c(mac, 255)
  123. self.assertRaises(ValueError, h.verify, wrong_mac)
  124. def test_hexverify(self):
  125. h = self.BLAKE2.new(digest_bytes=self.max_bytes, key=b"4")
  126. mac = h.hexdigest()
  127. h.hexverify(mac)
  128. self.assertRaises(ValueError, h.hexverify, "4556")
  129. def test_oid(self):
  130. prefix = "1.3.6.1.4.1.1722.12.2." + self.oid_variant + "."
  131. for digest_bits in self.digest_bits_oid:
  132. h = self.BLAKE2.new(digest_bits=digest_bits)
  133. self.assertEqual(h.oid, prefix + str(digest_bits // 8))
  134. h = self.BLAKE2.new(digest_bits=digest_bits, key=b"secret")
  135. self.assertRaises(AttributeError, lambda: h.oid)
  136. for digest_bits in (8, self.max_bits):
  137. if digest_bits in self.digest_bits_oid:
  138. continue
  139. self.assertRaises(AttributeError, lambda: h.oid)
  140. def test_bytearray(self):
  141. key = b'0' * 16
  142. data = b"\x00\x01\x02"
  143. # Data and key can be a bytearray (during initialization)
  144. key_ba = bytearray(key)
  145. data_ba = bytearray(data)
  146. h1 = self.BLAKE2.new(data=data, key=key)
  147. h2 = self.BLAKE2.new(data=data_ba, key=key_ba)
  148. key_ba[:1] = b'\xFF'
  149. data_ba[:1] = b'\xFF'
  150. self.assertEqual(h1.digest(), h2.digest())
  151. # Data can be a bytearray (during operation)
  152. data_ba = bytearray(data)
  153. h1 = self.BLAKE2.new()
  154. h2 = self.BLAKE2.new()
  155. h1.update(data)
  156. h2.update(data_ba)
  157. data_ba[:1] = b'\xFF'
  158. self.assertEqual(h1.digest(), h2.digest())
  159. def test_memoryview(self):
  160. key = b'0' * 16
  161. data = b"\x00\x01\x02"
  162. def get_mv_ro(data):
  163. return memoryview(data)
  164. def get_mv_rw(data):
  165. return memoryview(bytearray(data))
  166. for get_mv in (get_mv_ro, get_mv_rw):
  167. # Data and key can be a memoryview (during initialization)
  168. key_mv = get_mv(key)
  169. data_mv = get_mv(data)
  170. h1 = self.BLAKE2.new(data=data, key=key)
  171. h2 = self.BLAKE2.new(data=data_mv, key=key_mv)
  172. if not data_mv.readonly:
  173. data_mv[:1] = b'\xFF'
  174. key_mv[:1] = b'\xFF'
  175. self.assertEqual(h1.digest(), h2.digest())
  176. # Data can be a memoryview (during operation)
  177. data_mv = get_mv(data)
  178. h1 = self.BLAKE2.new()
  179. h2 = self.BLAKE2.new()
  180. h1.update(data)
  181. h2.update(data_mv)
  182. if not data_mv.readonly:
  183. data_mv[:1] = b'\xFF'
  184. self.assertEqual(h1.digest(), h2.digest())
  185. import sys
  186. if sys.version[:3] == "2.6":
  187. del test_memoryview
  188. class Blake2bTest(Blake2Test):
  189. #: Module
  190. BLAKE2 = BLAKE2b
  191. #: Max output size (in bits)
  192. max_bits = 512
  193. #: Max output size (in bytes)
  194. max_bytes = 64
  195. #: Bit size of the digests for which an ASN OID exists
  196. digest_bits_oid = (160, 256, 384, 512)
  197. # http://tools.ietf.org/html/draft-saarinen-blake2-02
  198. oid_variant = "1"
  199. class Blake2sTest(Blake2Test):
  200. #: Module
  201. BLAKE2 = BLAKE2s
  202. #: Max output size (in bits)
  203. max_bits = 256
  204. #: Max output size (in bytes)
  205. max_bytes = 32
  206. #: Bit size of the digests for which an ASN OID exists
  207. digest_bits_oid = (128, 160, 224, 256)
  208. # http://tools.ietf.org/html/draft-saarinen-blake2-02
  209. oid_variant = "2"
  210. class Blake2OfficialTestVector(unittest.TestCase):
  211. def setUp(self):
  212. test_vector_file = pycryptodome_filename(
  213. ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
  214. self.name.lower() + "-test.txt")
  215. expected = "in"
  216. self.test_vectors = []
  217. with open(test_vector_file, "rt") as test_vector_fd:
  218. for line_number, line in enumerate(test_vector_fd):
  219. if line.strip() == "" or line.startswith("#"):
  220. continue
  221. res = re.match("%s:\t([0-9A-Fa-f]*)" % expected, line)
  222. if not res:
  223. raise ValueError("Incorrect test vector format (line %d)"
  224. % line_number)
  225. if res.group(1):
  226. bin_value = unhexlify(tobytes(res.group(1)))
  227. else:
  228. bin_value = b""
  229. if expected == "in":
  230. input_data = bin_value
  231. expected = "key"
  232. elif expected == "key":
  233. key = bin_value
  234. expected = "hash"
  235. else:
  236. result = bin_value
  237. expected = "in"
  238. self.test_vectors.append((input_data, key, result))
  239. def runTest(self):
  240. for (input_data, key, result) in self.test_vectors:
  241. mac = self.BLAKE2.new(key=key, digest_bytes=self.max_bytes)
  242. mac.update(input_data)
  243. self.assertEqual(mac.digest(), result)
  244. class Blake2bOfficialTestVector(Blake2OfficialTestVector):
  245. #: Module
  246. BLAKE2 = BLAKE2b
  247. #: Hash name
  248. name = "BLAKE2b"
  249. #: Max digest size
  250. max_bytes = 64
  251. class Blake2sOfficialTestVector(Blake2OfficialTestVector):
  252. #: Module
  253. BLAKE2 = BLAKE2s
  254. #: Hash name
  255. name = "BLAKE2s"
  256. #: Max digest size
  257. max_bytes = 32
  258. class Blake2TestVector1(unittest.TestCase):
  259. def setUp(self):
  260. test_vector_file = pycryptodome_filename(
  261. ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
  262. "tv1.txt")
  263. self.test_vectors = []
  264. with open(test_vector_file, "rt") as test_vector_fd:
  265. for line_number, line in enumerate(test_vector_fd):
  266. if line.strip() == "" or line.startswith("#"):
  267. continue
  268. res = re.match("digest: ([0-9A-Fa-f]*)", line)
  269. if not res:
  270. raise ValueError("Incorrect test vector format (line %d)"
  271. % line_number)
  272. self.test_vectors.append(unhexlify(tobytes(res.group(1))))
  273. def runTest(self):
  274. for tv in self.test_vectors:
  275. digest_bytes = len(tv)
  276. next_data = b""
  277. for _ in range(100):
  278. h = self.BLAKE2.new(digest_bytes=digest_bytes)
  279. h.update(next_data)
  280. next_data = h.digest() + next_data
  281. self.assertEqual(h.digest(), tv)
  282. class Blake2bTestVector1(Blake2TestVector1):
  283. #: Module
  284. BLAKE2 = BLAKE2b
  285. #: Hash name
  286. name = "BLAKE2b"
  287. class Blake2sTestVector1(Blake2TestVector1):
  288. #: Module
  289. BLAKE2 = BLAKE2s
  290. #: Hash name
  291. name = "BLAKE2s"
  292. class Blake2TestVector2(unittest.TestCase):
  293. def setUp(self):
  294. test_vector_file = pycryptodome_filename(
  295. ("Crypto", "SelfTest", "Hash", "test_vectors", self.name),
  296. "tv2.txt")
  297. self.test_vectors = []
  298. with open(test_vector_file, "rt") as test_vector_fd:
  299. for line_number, line in enumerate(test_vector_fd):
  300. if line.strip() == "" or line.startswith("#"):
  301. continue
  302. res = re.match(r"digest\(([0-9]+)\): ([0-9A-Fa-f]*)", line)
  303. if not res:
  304. raise ValueError("Incorrect test vector format (line %d)"
  305. % line_number)
  306. key_size = int(res.group(1))
  307. result = unhexlify(tobytes(res.group(2)))
  308. self.test_vectors.append((key_size, result))
  309. def runTest(self):
  310. for key_size, result in self.test_vectors:
  311. next_data = b""
  312. for _ in range(100):
  313. h = self.BLAKE2.new(digest_bytes=self.max_bytes,
  314. key=b"A" * key_size)
  315. h.update(next_data)
  316. next_data = h.digest() + next_data
  317. self.assertEqual(h.digest(), result)
  318. class Blake2bTestVector2(Blake2TestVector1):
  319. #: Module
  320. BLAKE2 = BLAKE2b
  321. #: Hash name
  322. name = "BLAKE2b"
  323. #: Max digest size in bytes
  324. max_bytes = 64
  325. class Blake2sTestVector2(Blake2TestVector1):
  326. #: Module
  327. BLAKE2 = BLAKE2s
  328. #: Hash name
  329. name = "BLAKE2s"
  330. #: Max digest size in bytes
  331. max_bytes = 32
  332. def get_tests(config={}):
  333. tests = []
  334. tests += list_test_cases(Blake2bTest)
  335. tests.append(Blake2bOfficialTestVector())
  336. tests.append(Blake2bTestVector1())
  337. tests.append(Blake2bTestVector2())
  338. tests += list_test_cases(Blake2sTest)
  339. tests.append(Blake2sOfficialTestVector())
  340. tests.append(Blake2sTestVector1())
  341. tests.append(Blake2sTestVector2())
  342. return tests
  343. if __name__ == '__main__':
  344. import unittest
  345. suite = lambda: unittest.TestSuite(get_tests())
  346. unittest.main(defaultTest='suite')