test_BLAKE2.py 16 KB

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