test_hashlib.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. # Test hashlib module
  2. #
  3. # $Id$
  4. #
  5. # Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
  6. # Licensed to PSF under a Contributor Agreement.
  7. #
  8. import array
  9. from binascii import unhexlify
  10. import hashlib
  11. import importlib
  12. import io
  13. import itertools
  14. import os
  15. import sys
  16. import sysconfig
  17. import threading
  18. import unittest
  19. import warnings
  20. from test import support
  21. from test.support import _4G, bigmemtest
  22. from test.support.import_helper import import_fresh_module
  23. from test.support import os_helper
  24. from test.support import threading_helper
  25. from test.support import warnings_helper
  26. from http.client import HTTPException
  27. # Were we compiled --with-pydebug or with #define Py_DEBUG?
  28. COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
  29. # default builtin hash module
  30. default_builtin_hashes = {'md5', 'sha1', 'sha256', 'sha512', 'sha3', 'blake2'}
  31. # --with-builtin-hashlib-hashes override
  32. builtin_hashes = sysconfig.get_config_var("PY_BUILTIN_HASHLIB_HASHES")
  33. if builtin_hashes is None:
  34. builtin_hashes = default_builtin_hashes
  35. else:
  36. builtin_hashes = {
  37. m.strip() for m in builtin_hashes.strip('"').lower().split(",")
  38. }
  39. # hashlib with and without OpenSSL backend for PBKDF2
  40. # only import builtin_hashlib when all builtin hashes are available.
  41. # Otherwise import prints noise on stderr
  42. openssl_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
  43. if builtin_hashes == default_builtin_hashes:
  44. builtin_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
  45. else:
  46. builtin_hashlib = None
  47. try:
  48. from _hashlib import HASH, HASHXOF, openssl_md_meth_names, get_fips_mode
  49. except ImportError:
  50. HASH = None
  51. HASHXOF = None
  52. openssl_md_meth_names = frozenset()
  53. def get_fips_mode():
  54. return 0
  55. try:
  56. import _blake2
  57. except ImportError:
  58. _blake2 = None
  59. requires_blake2 = unittest.skipUnless(_blake2, 'requires _blake2')
  60. # bpo-46913: Don't test the _sha3 extension on a Python UBSAN build
  61. SKIP_SHA3 = support.check_sanitizer(ub=True)
  62. requires_sha3 = unittest.skipUnless(not SKIP_SHA3, 'requires _sha3')
  63. def hexstr(s):
  64. assert isinstance(s, bytes), repr(s)
  65. h = "0123456789abcdef"
  66. r = ''
  67. for i in s:
  68. r += h[(i >> 4) & 0xF] + h[i & 0xF]
  69. return r
  70. URL = "http://www.pythontest.net/hashlib/{}.txt"
  71. def read_vectors(hash_name):
  72. url = URL.format(hash_name)
  73. try:
  74. testdata = support.open_urlresource(url, encoding="utf-8")
  75. except (OSError, HTTPException):
  76. raise unittest.SkipTest("Could not retrieve {}".format(url))
  77. with testdata:
  78. for line in testdata:
  79. line = line.strip()
  80. if line.startswith('#') or not line:
  81. continue
  82. parts = line.split(',')
  83. parts[0] = bytes.fromhex(parts[0])
  84. yield parts
  85. class HashLibTestCase(unittest.TestCase):
  86. supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
  87. 'sha224', 'SHA224', 'sha256', 'SHA256',
  88. 'sha384', 'SHA384', 'sha512', 'SHA512',
  89. 'blake2b', 'blake2s',
  90. 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
  91. 'shake_128', 'shake_256')
  92. shakes = {'shake_128', 'shake_256'}
  93. # Issue #14693: fallback modules are always compiled under POSIX
  94. _warn_on_extension_import = os.name == 'posix' or COMPILED_WITH_PYDEBUG
  95. def _conditional_import_module(self, module_name):
  96. """Import a module and return a reference to it or None on failure."""
  97. try:
  98. return importlib.import_module(module_name)
  99. except ModuleNotFoundError as error:
  100. if self._warn_on_extension_import and module_name in builtin_hashes:
  101. warnings.warn('Did a C extension fail to compile? %s' % error)
  102. return None
  103. def __init__(self, *args, **kwargs):
  104. algorithms = set()
  105. for algorithm in self.supported_hash_names:
  106. algorithms.add(algorithm.lower())
  107. _blake2 = self._conditional_import_module('_blake2')
  108. if _blake2:
  109. algorithms.update({'blake2b', 'blake2s'})
  110. self.constructors_to_test = {}
  111. for algorithm in algorithms:
  112. if SKIP_SHA3 and algorithm.startswith('sha3_'):
  113. continue
  114. self.constructors_to_test[algorithm] = set()
  115. # For each algorithm, test the direct constructor and the use
  116. # of hashlib.new given the algorithm name.
  117. for algorithm, constructors in self.constructors_to_test.items():
  118. constructors.add(getattr(hashlib, algorithm))
  119. def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, **kwargs):
  120. if data is None:
  121. return hashlib.new(_alg, **kwargs)
  122. return hashlib.new(_alg, data, **kwargs)
  123. constructors.add(_test_algorithm_via_hashlib_new)
  124. _hashlib = self._conditional_import_module('_hashlib')
  125. self._hashlib = _hashlib
  126. if _hashlib:
  127. # These two algorithms should always be present when this module
  128. # is compiled. If not, something was compiled wrong.
  129. self.assertTrue(hasattr(_hashlib, 'openssl_md5'))
  130. self.assertTrue(hasattr(_hashlib, 'openssl_sha1'))
  131. for algorithm, constructors in self.constructors_to_test.items():
  132. constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
  133. if constructor:
  134. try:
  135. constructor()
  136. except ValueError:
  137. # default constructor blocked by crypto policy
  138. pass
  139. else:
  140. constructors.add(constructor)
  141. def add_builtin_constructor(name):
  142. constructor = getattr(hashlib, "__get_builtin_constructor")(name)
  143. self.constructors_to_test[name].add(constructor)
  144. _md5 = self._conditional_import_module('_md5')
  145. if _md5:
  146. add_builtin_constructor('md5')
  147. _sha1 = self._conditional_import_module('_sha1')
  148. if _sha1:
  149. add_builtin_constructor('sha1')
  150. _sha256 = self._conditional_import_module('_sha256')
  151. if _sha256:
  152. add_builtin_constructor('sha224')
  153. add_builtin_constructor('sha256')
  154. _sha512 = self._conditional_import_module('_sha512')
  155. if _sha512:
  156. add_builtin_constructor('sha384')
  157. add_builtin_constructor('sha512')
  158. if _blake2:
  159. add_builtin_constructor('blake2s')
  160. add_builtin_constructor('blake2b')
  161. if not SKIP_SHA3:
  162. _sha3 = self._conditional_import_module('_sha3')
  163. if _sha3:
  164. add_builtin_constructor('sha3_224')
  165. add_builtin_constructor('sha3_256')
  166. add_builtin_constructor('sha3_384')
  167. add_builtin_constructor('sha3_512')
  168. add_builtin_constructor('shake_128')
  169. add_builtin_constructor('shake_256')
  170. super(HashLibTestCase, self).__init__(*args, **kwargs)
  171. @property
  172. def hash_constructors(self):
  173. constructors = self.constructors_to_test.values()
  174. return itertools.chain.from_iterable(constructors)
  175. @property
  176. def is_fips_mode(self):
  177. return get_fips_mode()
  178. def test_hash_array(self):
  179. a = array.array("b", range(10))
  180. for cons in self.hash_constructors:
  181. c = cons(a, usedforsecurity=False)
  182. if c.name in self.shakes:
  183. c.hexdigest(16)
  184. else:
  185. c.hexdigest()
  186. def test_algorithms_guaranteed(self):
  187. self.assertEqual(hashlib.algorithms_guaranteed,
  188. set(_algo for _algo in self.supported_hash_names
  189. if _algo.islower()))
  190. def test_algorithms_available(self):
  191. self.assertTrue(set(hashlib.algorithms_guaranteed).
  192. issubset(hashlib.algorithms_available))
  193. # all available algorithms must be loadable, bpo-47101
  194. self.assertNotIn("undefined", hashlib.algorithms_available)
  195. for name in hashlib.algorithms_available:
  196. digest = hashlib.new(name, usedforsecurity=False)
  197. def test_usedforsecurity_true(self):
  198. hashlib.new("sha256", usedforsecurity=True)
  199. if self.is_fips_mode:
  200. self.skipTest("skip in FIPS mode")
  201. for cons in self.hash_constructors:
  202. cons(usedforsecurity=True)
  203. cons(b'', usedforsecurity=True)
  204. hashlib.new("md5", usedforsecurity=True)
  205. hashlib.md5(usedforsecurity=True)
  206. if self._hashlib is not None:
  207. self._hashlib.new("md5", usedforsecurity=True)
  208. self._hashlib.openssl_md5(usedforsecurity=True)
  209. def test_usedforsecurity_false(self):
  210. hashlib.new("sha256", usedforsecurity=False)
  211. for cons in self.hash_constructors:
  212. cons(usedforsecurity=False)
  213. cons(b'', usedforsecurity=False)
  214. hashlib.new("md5", usedforsecurity=False)
  215. hashlib.md5(usedforsecurity=False)
  216. if self._hashlib is not None:
  217. self._hashlib.new("md5", usedforsecurity=False)
  218. self._hashlib.openssl_md5(usedforsecurity=False)
  219. def test_unknown_hash(self):
  220. self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
  221. self.assertRaises(TypeError, hashlib.new, 1)
  222. def test_new_upper_to_lower(self):
  223. self.assertEqual(hashlib.new("SHA256").name, "sha256")
  224. def test_get_builtin_constructor(self):
  225. get_builtin_constructor = getattr(hashlib,
  226. '__get_builtin_constructor')
  227. builtin_constructor_cache = getattr(hashlib,
  228. '__builtin_constructor_cache')
  229. self.assertRaises(ValueError, get_builtin_constructor, 'test')
  230. try:
  231. import _md5
  232. except ImportError:
  233. self.skipTest("_md5 module not available")
  234. # This forces an ImportError for "import _md5" statements
  235. sys.modules['_md5'] = None
  236. # clear the cache
  237. builtin_constructor_cache.clear()
  238. try:
  239. self.assertRaises(ValueError, get_builtin_constructor, 'md5')
  240. finally:
  241. if '_md5' in locals():
  242. sys.modules['_md5'] = _md5
  243. else:
  244. del sys.modules['_md5']
  245. self.assertRaises(TypeError, get_builtin_constructor, 3)
  246. constructor = get_builtin_constructor('md5')
  247. self.assertIs(constructor, _md5.md5)
  248. self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5'])
  249. def test_hexdigest(self):
  250. for cons in self.hash_constructors:
  251. h = cons(usedforsecurity=False)
  252. if h.name in self.shakes:
  253. self.assertIsInstance(h.digest(16), bytes)
  254. self.assertEqual(hexstr(h.digest(16)), h.hexdigest(16))
  255. else:
  256. self.assertIsInstance(h.digest(), bytes)
  257. self.assertEqual(hexstr(h.digest()), h.hexdigest())
  258. def test_digest_length_overflow(self):
  259. # See issue #34922
  260. large_sizes = (2**29, 2**32-10, 2**32+10, 2**61, 2**64-10, 2**64+10)
  261. for cons in self.hash_constructors:
  262. h = cons(usedforsecurity=False)
  263. if h.name not in self.shakes:
  264. continue
  265. if HASH is not None and isinstance(h, HASH):
  266. # _hashopenssl's take a size_t
  267. continue
  268. for digest in h.digest, h.hexdigest:
  269. self.assertRaises(ValueError, digest, -10)
  270. for length in large_sizes:
  271. with self.assertRaises((ValueError, OverflowError)):
  272. digest(length)
  273. def test_name_attribute(self):
  274. for cons in self.hash_constructors:
  275. h = cons(usedforsecurity=False)
  276. self.assertIsInstance(h.name, str)
  277. if h.name in self.supported_hash_names:
  278. self.assertIn(h.name, self.supported_hash_names)
  279. else:
  280. self.assertNotIn(h.name, self.supported_hash_names)
  281. self.assertEqual(
  282. h.name,
  283. hashlib.new(h.name, usedforsecurity=False).name
  284. )
  285. def test_large_update(self):
  286. aas = b'a' * 128
  287. bees = b'b' * 127
  288. cees = b'c' * 126
  289. dees = b'd' * 2048 # HASHLIB_GIL_MINSIZE
  290. for cons in self.hash_constructors:
  291. m1 = cons(usedforsecurity=False)
  292. m1.update(aas)
  293. m1.update(bees)
  294. m1.update(cees)
  295. m1.update(dees)
  296. if m1.name in self.shakes:
  297. args = (16,)
  298. else:
  299. args = ()
  300. m2 = cons(usedforsecurity=False)
  301. m2.update(aas + bees + cees + dees)
  302. self.assertEqual(m1.digest(*args), m2.digest(*args))
  303. m3 = cons(aas + bees + cees + dees, usedforsecurity=False)
  304. self.assertEqual(m1.digest(*args), m3.digest(*args))
  305. # verify copy() doesn't touch original
  306. m4 = cons(aas + bees + cees, usedforsecurity=False)
  307. m4_digest = m4.digest(*args)
  308. m4_copy = m4.copy()
  309. m4_copy.update(dees)
  310. self.assertEqual(m1.digest(*args), m4_copy.digest(*args))
  311. self.assertEqual(m4.digest(*args), m4_digest)
  312. def check(self, name, data, hexdigest, shake=False, **kwargs):
  313. length = len(hexdigest)//2
  314. hexdigest = hexdigest.lower()
  315. constructors = self.constructors_to_test[name]
  316. # 2 is for hashlib.name(...) and hashlib.new(name, ...)
  317. self.assertGreaterEqual(len(constructors), 2)
  318. for hash_object_constructor in constructors:
  319. m = hash_object_constructor(data, **kwargs)
  320. computed = m.hexdigest() if not shake else m.hexdigest(length)
  321. self.assertEqual(
  322. computed, hexdigest,
  323. "Hash algorithm %s constructed using %s returned hexdigest"
  324. " %r for %d byte input data that should have hashed to %r."
  325. % (name, hash_object_constructor,
  326. computed, len(data), hexdigest))
  327. computed = m.digest() if not shake else m.digest(length)
  328. digest = bytes.fromhex(hexdigest)
  329. self.assertEqual(computed, digest)
  330. if not shake:
  331. self.assertEqual(len(digest), m.digest_size)
  332. if not shake and kwargs.get("key") is None:
  333. # skip shake and blake2 extended parameter tests
  334. self.check_file_digest(name, data, hexdigest)
  335. def check_file_digest(self, name, data, hexdigest):
  336. hexdigest = hexdigest.lower()
  337. try:
  338. hashlib.new(name)
  339. except ValueError:
  340. # skip, algorithm is blocked by security policy.
  341. return
  342. digests = [name]
  343. digests.extend(self.constructors_to_test[name])
  344. with open(os_helper.TESTFN, "wb") as f:
  345. f.write(data)
  346. try:
  347. for digest in digests:
  348. buf = io.BytesIO(data)
  349. buf.seek(0)
  350. self.assertEqual(
  351. hashlib.file_digest(buf, digest).hexdigest(), hexdigest
  352. )
  353. with open(os_helper.TESTFN, "rb") as f:
  354. digestobj = hashlib.file_digest(f, digest)
  355. self.assertEqual(digestobj.hexdigest(), hexdigest)
  356. finally:
  357. os.unlink(os_helper.TESTFN)
  358. def check_no_unicode(self, algorithm_name):
  359. # Unicode objects are not allowed as input.
  360. constructors = self.constructors_to_test[algorithm_name]
  361. for hash_object_constructor in constructors:
  362. self.assertRaises(TypeError, hash_object_constructor, 'spam')
  363. def test_no_unicode(self):
  364. self.check_no_unicode('md5')
  365. self.check_no_unicode('sha1')
  366. self.check_no_unicode('sha224')
  367. self.check_no_unicode('sha256')
  368. self.check_no_unicode('sha384')
  369. self.check_no_unicode('sha512')
  370. @requires_blake2
  371. def test_no_unicode_blake2(self):
  372. self.check_no_unicode('blake2b')
  373. self.check_no_unicode('blake2s')
  374. @requires_sha3
  375. def test_no_unicode_sha3(self):
  376. self.check_no_unicode('sha3_224')
  377. self.check_no_unicode('sha3_256')
  378. self.check_no_unicode('sha3_384')
  379. self.check_no_unicode('sha3_512')
  380. self.check_no_unicode('shake_128')
  381. self.check_no_unicode('shake_256')
  382. def check_blocksize_name(self, name, block_size=0, digest_size=0,
  383. digest_length=None):
  384. constructors = self.constructors_to_test[name]
  385. for hash_object_constructor in constructors:
  386. m = hash_object_constructor(usedforsecurity=False)
  387. self.assertEqual(m.block_size, block_size)
  388. self.assertEqual(m.digest_size, digest_size)
  389. if digest_length:
  390. self.assertEqual(len(m.digest(digest_length)),
  391. digest_length)
  392. self.assertEqual(len(m.hexdigest(digest_length)),
  393. 2*digest_length)
  394. else:
  395. self.assertEqual(len(m.digest()), digest_size)
  396. self.assertEqual(len(m.hexdigest()), 2*digest_size)
  397. self.assertEqual(m.name, name)
  398. # split for sha3_512 / _sha3.sha3 object
  399. self.assertIn(name.split("_")[0], repr(m))
  400. def test_blocksize_name(self):
  401. self.check_blocksize_name('md5', 64, 16)
  402. self.check_blocksize_name('sha1', 64, 20)
  403. self.check_blocksize_name('sha224', 64, 28)
  404. self.check_blocksize_name('sha256', 64, 32)
  405. self.check_blocksize_name('sha384', 128, 48)
  406. self.check_blocksize_name('sha512', 128, 64)
  407. @requires_sha3
  408. def test_blocksize_name_sha3(self):
  409. self.check_blocksize_name('sha3_224', 144, 28)
  410. self.check_blocksize_name('sha3_256', 136, 32)
  411. self.check_blocksize_name('sha3_384', 104, 48)
  412. self.check_blocksize_name('sha3_512', 72, 64)
  413. self.check_blocksize_name('shake_128', 168, 0, 32)
  414. self.check_blocksize_name('shake_256', 136, 0, 64)
  415. def check_sha3(self, name, capacity, rate, suffix):
  416. constructors = self.constructors_to_test[name]
  417. for hash_object_constructor in constructors:
  418. m = hash_object_constructor()
  419. if HASH is not None and isinstance(m, HASH):
  420. # _hashopenssl's variant does not have extra SHA3 attributes
  421. continue
  422. self.assertEqual(capacity + rate, 1600)
  423. self.assertEqual(m._capacity_bits, capacity)
  424. self.assertEqual(m._rate_bits, rate)
  425. self.assertEqual(m._suffix, suffix)
  426. @requires_sha3
  427. def test_extra_sha3(self):
  428. self.check_sha3('sha3_224', 448, 1152, b'\x06')
  429. self.check_sha3('sha3_256', 512, 1088, b'\x06')
  430. self.check_sha3('sha3_384', 768, 832, b'\x06')
  431. self.check_sha3('sha3_512', 1024, 576, b'\x06')
  432. self.check_sha3('shake_128', 256, 1344, b'\x1f')
  433. self.check_sha3('shake_256', 512, 1088, b'\x1f')
  434. @requires_blake2
  435. def test_blocksize_name_blake2(self):
  436. self.check_blocksize_name('blake2b', 128, 64)
  437. self.check_blocksize_name('blake2s', 64, 32)
  438. def test_case_md5_0(self):
  439. self.check(
  440. 'md5', b'', 'd41d8cd98f00b204e9800998ecf8427e',
  441. usedforsecurity=False
  442. )
  443. def test_case_md5_1(self):
  444. self.check(
  445. 'md5', b'abc', '900150983cd24fb0d6963f7d28e17f72',
  446. usedforsecurity=False
  447. )
  448. def test_case_md5_2(self):
  449. self.check(
  450. 'md5',
  451. b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
  452. 'd174ab98d277d9f5a5611c2c9f419d9f',
  453. usedforsecurity=False
  454. )
  455. @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
  456. @bigmemtest(size=_4G + 5, memuse=1, dry_run=False)
  457. def test_case_md5_huge(self, size):
  458. self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
  459. @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems')
  460. @bigmemtest(size=_4G - 1, memuse=1, dry_run=False)
  461. def test_case_md5_uintmax(self, size):
  462. self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
  463. # use the three examples from Federal Information Processing Standards
  464. # Publication 180-1, Secure Hash Standard, 1995 April 17
  465. # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
  466. def test_case_sha1_0(self):
  467. self.check('sha1', b"",
  468. "da39a3ee5e6b4b0d3255bfef95601890afd80709")
  469. def test_case_sha1_1(self):
  470. self.check('sha1', b"abc",
  471. "a9993e364706816aba3e25717850c26c9cd0d89d")
  472. def test_case_sha1_2(self):
  473. self.check('sha1',
  474. b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  475. "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
  476. def test_case_sha1_3(self):
  477. self.check('sha1', b"a" * 1000000,
  478. "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
  479. # use the examples from Federal Information Processing Standards
  480. # Publication 180-2, Secure Hash Standard, 2002 August 1
  481. # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
  482. def test_case_sha224_0(self):
  483. self.check('sha224', b"",
  484. "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
  485. def test_case_sha224_1(self):
  486. self.check('sha224', b"abc",
  487. "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
  488. def test_case_sha224_2(self):
  489. self.check('sha224',
  490. b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  491. "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
  492. def test_case_sha224_3(self):
  493. self.check('sha224', b"a" * 1000000,
  494. "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
  495. def test_case_sha256_0(self):
  496. self.check('sha256', b"",
  497. "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
  498. def test_case_sha256_1(self):
  499. self.check('sha256', b"abc",
  500. "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
  501. def test_case_sha256_2(self):
  502. self.check('sha256',
  503. b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  504. "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
  505. def test_case_sha256_3(self):
  506. self.check('sha256', b"a" * 1000000,
  507. "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
  508. def test_case_sha384_0(self):
  509. self.check('sha384', b"",
  510. "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
  511. "274edebfe76f65fbd51ad2f14898b95b")
  512. def test_case_sha384_1(self):
  513. self.check('sha384', b"abc",
  514. "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
  515. "8086072ba1e7cc2358baeca134c825a7")
  516. def test_case_sha384_2(self):
  517. self.check('sha384',
  518. b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
  519. b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
  520. "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
  521. "fcc7c71a557e2db966c3e9fa91746039")
  522. def test_case_sha384_3(self):
  523. self.check('sha384', b"a" * 1000000,
  524. "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
  525. "07b8b3dc38ecc4ebae97ddd87f3d8985")
  526. def test_case_sha512_0(self):
  527. self.check('sha512', b"",
  528. "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
  529. "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
  530. def test_case_sha512_1(self):
  531. self.check('sha512', b"abc",
  532. "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
  533. "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
  534. def test_case_sha512_2(self):
  535. self.check('sha512',
  536. b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
  537. b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
  538. "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
  539. "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
  540. def test_case_sha512_3(self):
  541. self.check('sha512', b"a" * 1000000,
  542. "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
  543. "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
  544. def check_blake2(self, constructor, salt_size, person_size, key_size,
  545. digest_size, max_offset):
  546. self.assertEqual(constructor.SALT_SIZE, salt_size)
  547. for i in range(salt_size + 1):
  548. constructor(salt=b'a' * i)
  549. salt = b'a' * (salt_size + 1)
  550. self.assertRaises(ValueError, constructor, salt=salt)
  551. self.assertEqual(constructor.PERSON_SIZE, person_size)
  552. for i in range(person_size+1):
  553. constructor(person=b'a' * i)
  554. person = b'a' * (person_size + 1)
  555. self.assertRaises(ValueError, constructor, person=person)
  556. self.assertEqual(constructor.MAX_DIGEST_SIZE, digest_size)
  557. for i in range(1, digest_size + 1):
  558. constructor(digest_size=i)
  559. self.assertRaises(ValueError, constructor, digest_size=-1)
  560. self.assertRaises(ValueError, constructor, digest_size=0)
  561. self.assertRaises(ValueError, constructor, digest_size=digest_size+1)
  562. self.assertEqual(constructor.MAX_KEY_SIZE, key_size)
  563. for i in range(key_size+1):
  564. constructor(key=b'a' * i)
  565. key = b'a' * (key_size + 1)
  566. self.assertRaises(ValueError, constructor, key=key)
  567. self.assertEqual(constructor().hexdigest(),
  568. constructor(key=b'').hexdigest())
  569. for i in range(0, 256):
  570. constructor(fanout=i)
  571. self.assertRaises(ValueError, constructor, fanout=-1)
  572. self.assertRaises(ValueError, constructor, fanout=256)
  573. for i in range(1, 256):
  574. constructor(depth=i)
  575. self.assertRaises(ValueError, constructor, depth=-1)
  576. self.assertRaises(ValueError, constructor, depth=0)
  577. self.assertRaises(ValueError, constructor, depth=256)
  578. for i in range(0, 256):
  579. constructor(node_depth=i)
  580. self.assertRaises(ValueError, constructor, node_depth=-1)
  581. self.assertRaises(ValueError, constructor, node_depth=256)
  582. for i in range(0, digest_size + 1):
  583. constructor(inner_size=i)
  584. self.assertRaises(ValueError, constructor, inner_size=-1)
  585. self.assertRaises(ValueError, constructor, inner_size=digest_size+1)
  586. constructor(leaf_size=0)
  587. constructor(leaf_size=(1<<32)-1)
  588. self.assertRaises(ValueError, constructor, leaf_size=-1)
  589. self.assertRaises(OverflowError, constructor, leaf_size=1<<32)
  590. constructor(node_offset=0)
  591. constructor(node_offset=max_offset)
  592. self.assertRaises(ValueError, constructor, node_offset=-1)
  593. self.assertRaises(OverflowError, constructor, node_offset=max_offset+1)
  594. self.assertRaises(TypeError, constructor, data=b'')
  595. self.assertRaises(TypeError, constructor, string=b'')
  596. self.assertRaises(TypeError, constructor, '')
  597. constructor(
  598. b'',
  599. key=b'',
  600. salt=b'',
  601. person=b'',
  602. digest_size=17,
  603. fanout=1,
  604. depth=1,
  605. leaf_size=256,
  606. node_offset=512,
  607. node_depth=1,
  608. inner_size=7,
  609. last_node=True
  610. )
  611. def blake2_rfc7693(self, constructor, md_len, in_len):
  612. def selftest_seq(length, seed):
  613. mask = (1<<32)-1
  614. a = (0xDEAD4BAD * seed) & mask
  615. b = 1
  616. out = bytearray(length)
  617. for i in range(length):
  618. t = (a + b) & mask
  619. a, b = b, t
  620. out[i] = (t >> 24) & 0xFF
  621. return out
  622. outer = constructor(digest_size=32)
  623. for outlen in md_len:
  624. for inlen in in_len:
  625. indata = selftest_seq(inlen, inlen)
  626. key = selftest_seq(outlen, outlen)
  627. unkeyed = constructor(indata, digest_size=outlen)
  628. outer.update(unkeyed.digest())
  629. keyed = constructor(indata, key=key, digest_size=outlen)
  630. outer.update(keyed.digest())
  631. return outer.hexdigest()
  632. @requires_blake2
  633. def test_blake2b(self):
  634. self.check_blake2(hashlib.blake2b, 16, 16, 64, 64, (1<<64)-1)
  635. b2b_md_len = [20, 32, 48, 64]
  636. b2b_in_len = [0, 3, 128, 129, 255, 1024]
  637. self.assertEqual(
  638. self.blake2_rfc7693(hashlib.blake2b, b2b_md_len, b2b_in_len),
  639. "c23a7800d98123bd10f506c61e29da5603d763b8bbad2e737f5e765a7bccd475")
  640. @requires_blake2
  641. def test_case_blake2b_0(self):
  642. self.check('blake2b', b"",
  643. "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419"+
  644. "d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce")
  645. @requires_blake2
  646. def test_case_blake2b_1(self):
  647. self.check('blake2b', b"abc",
  648. "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1"+
  649. "7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923")
  650. @requires_blake2
  651. def test_case_blake2b_all_parameters(self):
  652. # This checks that all the parameters work in general, and also that
  653. # parameter byte order doesn't get confused on big endian platforms.
  654. self.check('blake2b', b"foo",
  655. "920568b0c5873b2f0ab67bedb6cf1b2b",
  656. digest_size=16,
  657. key=b"bar",
  658. salt=b"baz",
  659. person=b"bing",
  660. fanout=2,
  661. depth=3,
  662. leaf_size=4,
  663. node_offset=5,
  664. node_depth=6,
  665. inner_size=7,
  666. last_node=True)
  667. @requires_blake2
  668. def test_blake2b_vectors(self):
  669. for msg, key, md in read_vectors('blake2b'):
  670. key = bytes.fromhex(key)
  671. self.check('blake2b', msg, md, key=key)
  672. @requires_blake2
  673. def test_blake2s(self):
  674. self.check_blake2(hashlib.blake2s, 8, 8, 32, 32, (1<<48)-1)
  675. b2s_md_len = [16, 20, 28, 32]
  676. b2s_in_len = [0, 3, 64, 65, 255, 1024]
  677. self.assertEqual(
  678. self.blake2_rfc7693(hashlib.blake2s, b2s_md_len, b2s_in_len),
  679. "6a411f08ce25adcdfb02aba641451cec53c598b24f4fc787fbdc88797f4c1dfe")
  680. @requires_blake2
  681. def test_case_blake2s_0(self):
  682. self.check('blake2s', b"",
  683. "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9")
  684. @requires_blake2
  685. def test_case_blake2s_1(self):
  686. self.check('blake2s', b"abc",
  687. "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982")
  688. @requires_blake2
  689. def test_case_blake2s_all_parameters(self):
  690. # This checks that all the parameters work in general, and also that
  691. # parameter byte order doesn't get confused on big endian platforms.
  692. self.check('blake2s', b"foo",
  693. "bf2a8f7fe3c555012a6f8046e646bc75",
  694. digest_size=16,
  695. key=b"bar",
  696. salt=b"baz",
  697. person=b"bing",
  698. fanout=2,
  699. depth=3,
  700. leaf_size=4,
  701. node_offset=5,
  702. node_depth=6,
  703. inner_size=7,
  704. last_node=True)
  705. @requires_blake2
  706. def test_blake2s_vectors(self):
  707. for msg, key, md in read_vectors('blake2s'):
  708. key = bytes.fromhex(key)
  709. self.check('blake2s', msg, md, key=key)
  710. @requires_sha3
  711. def test_case_sha3_224_0(self):
  712. self.check('sha3_224', b"",
  713. "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7")
  714. @requires_sha3
  715. def test_case_sha3_224_vector(self):
  716. for msg, md in read_vectors('sha3_224'):
  717. self.check('sha3_224', msg, md)
  718. @requires_sha3
  719. def test_case_sha3_256_0(self):
  720. self.check('sha3_256', b"",
  721. "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")
  722. @requires_sha3
  723. def test_case_sha3_256_vector(self):
  724. for msg, md in read_vectors('sha3_256'):
  725. self.check('sha3_256', msg, md)
  726. @requires_sha3
  727. def test_case_sha3_384_0(self):
  728. self.check('sha3_384', b"",
  729. "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2a"+
  730. "c3713831264adb47fb6bd1e058d5f004")
  731. @requires_sha3
  732. def test_case_sha3_384_vector(self):
  733. for msg, md in read_vectors('sha3_384'):
  734. self.check('sha3_384', msg, md)
  735. @requires_sha3
  736. def test_case_sha3_512_0(self):
  737. self.check('sha3_512', b"",
  738. "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6"+
  739. "15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26")
  740. @requires_sha3
  741. def test_case_sha3_512_vector(self):
  742. for msg, md in read_vectors('sha3_512'):
  743. self.check('sha3_512', msg, md)
  744. def test_case_shake_128_0(self):
  745. self.check('shake_128', b"",
  746. "7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26",
  747. True)
  748. self.check('shake_128', b"", "7f9c", True)
  749. def test_case_shake128_vector(self):
  750. for msg, md in read_vectors('shake_128'):
  751. self.check('shake_128', msg, md, True)
  752. def test_case_shake_256_0(self):
  753. self.check('shake_256', b"",
  754. "46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f",
  755. True)
  756. self.check('shake_256', b"", "46b9", True)
  757. def test_case_shake256_vector(self):
  758. for msg, md in read_vectors('shake_256'):
  759. self.check('shake_256', msg, md, True)
  760. def test_gil(self):
  761. # Check things work fine with an input larger than the size required
  762. # for multithreaded operation (which is hardwired to 2048).
  763. gil_minsize = 2048
  764. for cons in self.hash_constructors:
  765. m = cons(usedforsecurity=False)
  766. m.update(b'1')
  767. m.update(b'#' * gil_minsize)
  768. m.update(b'1')
  769. m = cons(b'x' * gil_minsize, usedforsecurity=False)
  770. m.update(b'1')
  771. m = hashlib.sha256()
  772. m.update(b'1')
  773. m.update(b'#' * gil_minsize)
  774. m.update(b'1')
  775. self.assertEqual(
  776. m.hexdigest(),
  777. '1cfceca95989f51f658e3f3ffe7f1cd43726c9e088c13ee10b46f57cef135b94'
  778. )
  779. m = hashlib.sha256(b'1' + b'#' * gil_minsize + b'1')
  780. self.assertEqual(
  781. m.hexdigest(),
  782. '1cfceca95989f51f658e3f3ffe7f1cd43726c9e088c13ee10b46f57cef135b94'
  783. )
  784. @threading_helper.reap_threads
  785. @threading_helper.requires_working_threading()
  786. def test_threaded_hashing(self):
  787. # Updating the same hash object from several threads at once
  788. # using data chunk sizes containing the same byte sequences.
  789. #
  790. # If the internal locks are working to prevent multiple
  791. # updates on the same object from running at once, the resulting
  792. # hash will be the same as doing it single threaded upfront.
  793. hasher = hashlib.sha1()
  794. num_threads = 5
  795. smallest_data = b'swineflu'
  796. data = smallest_data * 200000
  797. expected_hash = hashlib.sha1(data*num_threads).hexdigest()
  798. def hash_in_chunks(chunk_size):
  799. index = 0
  800. while index < len(data):
  801. hasher.update(data[index:index + chunk_size])
  802. index += chunk_size
  803. threads = []
  804. for threadnum in range(num_threads):
  805. chunk_size = len(data) // (10 ** threadnum)
  806. self.assertGreater(chunk_size, 0)
  807. self.assertEqual(chunk_size % len(smallest_data), 0)
  808. thread = threading.Thread(target=hash_in_chunks,
  809. args=(chunk_size,))
  810. threads.append(thread)
  811. for thread in threads:
  812. thread.start()
  813. for thread in threads:
  814. thread.join()
  815. self.assertEqual(expected_hash, hasher.hexdigest())
  816. def test_get_fips_mode(self):
  817. fips_mode = self.is_fips_mode
  818. if fips_mode is not None:
  819. self.assertIsInstance(fips_mode, int)
  820. @support.cpython_only
  821. def test_disallow_instantiation(self):
  822. for algorithm, constructors in self.constructors_to_test.items():
  823. if algorithm.startswith(("sha3_", "shake", "blake")):
  824. # _sha3 and _blake types can be instantiated
  825. continue
  826. # all other types have DISALLOW_INSTANTIATION
  827. for constructor in constructors:
  828. # In FIPS mode some algorithms are not available raising ValueError
  829. try:
  830. h = constructor()
  831. except ValueError:
  832. continue
  833. with self.subTest(constructor=constructor):
  834. support.check_disallow_instantiation(self, type(h))
  835. @unittest.skipUnless(HASH is not None, 'need _hashlib')
  836. def test_hash_disallow_instantiation(self):
  837. # internal types like _hashlib.HASH are not constructable
  838. support.check_disallow_instantiation(self, HASH)
  839. support.check_disallow_instantiation(self, HASHXOF)
  840. def test_readonly_types(self):
  841. for algorithm, constructors in self.constructors_to_test.items():
  842. # all other types have DISALLOW_INSTANTIATION
  843. for constructor in constructors:
  844. # In FIPS mode some algorithms are not available raising ValueError
  845. try:
  846. hash_type = type(constructor())
  847. except ValueError:
  848. continue
  849. with self.subTest(hash_type=hash_type):
  850. with self.assertRaisesRegex(TypeError, "immutable type"):
  851. hash_type.value = False
  852. class KDFTests(unittest.TestCase):
  853. pbkdf2_test_vectors = [
  854. (b'password', b'salt', 1, None),
  855. (b'password', b'salt', 2, None),
  856. (b'password', b'salt', 4096, None),
  857. # too slow, it takes over a minute on a fast CPU.
  858. #(b'password', b'salt', 16777216, None),
  859. (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt',
  860. 4096, -1),
  861. (b'pass\0word', b'sa\0lt', 4096, 16),
  862. ]
  863. scrypt_test_vectors = [
  864. (b'', b'', 16, 1, 1, unhexlify('77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906')),
  865. (b'password', b'NaCl', 1024, 8, 16, unhexlify('fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640')),
  866. (b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, unhexlify('7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887')),
  867. ]
  868. pbkdf2_results = {
  869. "sha1": [
  870. # official test vectors from RFC 6070
  871. (bytes.fromhex('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None),
  872. (bytes.fromhex('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None),
  873. (bytes.fromhex('4b007901b765489abead49d926f721d065a429c1'), None),
  874. #(bytes.fromhex('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None),
  875. (bytes.fromhex('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c'
  876. 'f2f07038'), 25),
  877. (bytes.fromhex('56fa6aa75548099dcc37d7f03425e0c3'), None),],
  878. "sha256": [
  879. (bytes.fromhex('120fb6cffcf8b32c43e7225256c4f837'
  880. 'a86548c92ccc35480805987cb70be17b'), None),
  881. (bytes.fromhex('ae4d0c95af6b46d32d0adff928f06dd0'
  882. '2a303f8ef3c251dfd6e2d85a95474c43'), None),
  883. (bytes.fromhex('c5e478d59288c841aa530db6845c4c8d'
  884. '962893a001ce4e11a4963873aa98134a'), None),
  885. #(bytes.fromhex('cf81c66fe8cfc04d1f31ecb65dab4089'
  886. # 'f7f179e89b3b0bcb17ad10e3ac6eba46'), None),
  887. (bytes.fromhex('348c89dbcbd32b2f32d814b8116e84cf2b17'
  888. '347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40),
  889. (bytes.fromhex('89b69d0516f829893c696226650a8687'), None),],
  890. "sha512": [
  891. (bytes.fromhex('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5'
  892. 'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f'
  893. '050235d7d68b1da55e63f73b60a57fce'), None),
  894. (bytes.fromhex('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071'
  895. '3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82'
  896. 'be67335c77a6068e04112754f27ccf4e'), None),
  897. (bytes.fromhex('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8'
  898. '7f6902e072f457b5143f30602641b3d55cd335988cb36b84'
  899. '376060ecd532e039b742a239434af2d5'), None),
  900. (bytes.fromhex('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8'
  901. '68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30'
  902. '225c583a186cd82bd4daea9724a3d3b8'), 64),
  903. (bytes.fromhex('9d9e9c4cd21fe4be24d5b8244c759665'), None),],
  904. }
  905. def _test_pbkdf2_hmac(self, pbkdf2, supported):
  906. for digest_name, results in self.pbkdf2_results.items():
  907. if digest_name not in supported:
  908. continue
  909. for i, vector in enumerate(self.pbkdf2_test_vectors):
  910. password, salt, rounds, dklen = vector
  911. expected, overwrite_dklen = results[i]
  912. if overwrite_dklen:
  913. dklen = overwrite_dklen
  914. out = pbkdf2(digest_name, password, salt, rounds, dklen)
  915. self.assertEqual(out, expected,
  916. (digest_name, password, salt, rounds, dklen))
  917. out = pbkdf2(digest_name, memoryview(password),
  918. memoryview(salt), rounds, dklen)
  919. self.assertEqual(out, expected)
  920. out = pbkdf2(digest_name, bytearray(password),
  921. bytearray(salt), rounds, dklen)
  922. self.assertEqual(out, expected)
  923. if dklen is None:
  924. out = pbkdf2(digest_name, password, salt, rounds)
  925. self.assertEqual(out, expected,
  926. (digest_name, password, salt, rounds))
  927. with self.assertRaisesRegex(ValueError, '.*unsupported.*'):
  928. pbkdf2('unknown', b'pass', b'salt', 1)
  929. if 'sha1' in supported:
  930. self.assertRaises(
  931. TypeError, pbkdf2, b'sha1', b'pass', b'salt', 1
  932. )
  933. self.assertRaises(
  934. TypeError, pbkdf2, 'sha1', 'pass', 'salt', 1
  935. )
  936. self.assertRaises(
  937. ValueError, pbkdf2, 'sha1', b'pass', b'salt', 0
  938. )
  939. self.assertRaises(
  940. ValueError, pbkdf2, 'sha1', b'pass', b'salt', -1
  941. )
  942. self.assertRaises(
  943. ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, 0
  944. )
  945. self.assertRaises(
  946. ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, -1
  947. )
  948. out = pbkdf2(hash_name='sha1', password=b'password', salt=b'salt',
  949. iterations=1, dklen=None)
  950. self.assertEqual(out, self.pbkdf2_results['sha1'][0][0])
  951. @unittest.skipIf(builtin_hashlib is None, "test requires builtin_hashlib")
  952. def test_pbkdf2_hmac_py(self):
  953. with warnings_helper.check_warnings():
  954. self._test_pbkdf2_hmac(
  955. builtin_hashlib.pbkdf2_hmac, builtin_hashes
  956. )
  957. @unittest.skipUnless(hasattr(openssl_hashlib, 'pbkdf2_hmac'),
  958. ' test requires OpenSSL > 1.0')
  959. def test_pbkdf2_hmac_c(self):
  960. self._test_pbkdf2_hmac(openssl_hashlib.pbkdf2_hmac, openssl_md_meth_names)
  961. @unittest.skipUnless(hasattr(hashlib, 'scrypt'),
  962. ' test requires OpenSSL > 1.1')
  963. @unittest.skipIf(get_fips_mode(), reason="scrypt is blocked in FIPS mode")
  964. def test_scrypt(self):
  965. for password, salt, n, r, p, expected in self.scrypt_test_vectors:
  966. result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p)
  967. self.assertEqual(result, expected)
  968. # this values should work
  969. hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1)
  970. # password and salt must be bytes-like
  971. with self.assertRaises(TypeError):
  972. hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1)
  973. with self.assertRaises(TypeError):
  974. hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1)
  975. # require keyword args
  976. with self.assertRaises(TypeError):
  977. hashlib.scrypt(b'password')
  978. with self.assertRaises(TypeError):
  979. hashlib.scrypt(b'password', b'salt')
  980. with self.assertRaises(TypeError):
  981. hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt')
  982. for n in [-1, 0, 1, None]:
  983. with self.assertRaises((ValueError, OverflowError, TypeError)):
  984. hashlib.scrypt(b'password', salt=b'salt', n=n, r=8, p=1)
  985. for r in [-1, 0, None]:
  986. with self.assertRaises((ValueError, OverflowError, TypeError)):
  987. hashlib.scrypt(b'password', salt=b'salt', n=2, r=r, p=1)
  988. for p in [-1, 0, None]:
  989. with self.assertRaises((ValueError, OverflowError, TypeError)):
  990. hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=p)
  991. for maxmem in [-1, None]:
  992. with self.assertRaises((ValueError, OverflowError, TypeError)):
  993. hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
  994. maxmem=maxmem)
  995. for dklen in [-1, None]:
  996. with self.assertRaises((ValueError, OverflowError, TypeError)):
  997. hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
  998. dklen=dklen)
  999. def test_normalized_name(self):
  1000. self.assertNotIn("blake2b512", hashlib.algorithms_available)
  1001. self.assertNotIn("sha3-512", hashlib.algorithms_available)
  1002. def test_file_digest(self):
  1003. data = b'a' * 65536
  1004. d1 = hashlib.sha256()
  1005. self.addCleanup(os.unlink, os_helper.TESTFN)
  1006. with open(os_helper.TESTFN, "wb") as f:
  1007. for _ in range(10):
  1008. d1.update(data)
  1009. f.write(data)
  1010. with open(os_helper.TESTFN, "rb") as f:
  1011. d2 = hashlib.file_digest(f, hashlib.sha256)
  1012. self.assertEqual(d1.hexdigest(), d2.hexdigest())
  1013. self.assertEqual(d1.name, d2.name)
  1014. self.assertIs(type(d1), type(d2))
  1015. with self.assertRaises(ValueError):
  1016. hashlib.file_digest(None, "sha256")
  1017. with self.assertRaises(ValueError):
  1018. with open(os_helper.TESTFN, "r") as f:
  1019. hashlib.file_digest(f, "sha256")
  1020. with self.assertRaises(ValueError):
  1021. with open(os_helper.TESTFN, "wb") as f:
  1022. hashlib.file_digest(f, "sha256")
  1023. if __name__ == "__main__":
  1024. unittest.main()