test_hashlib.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. import hashlib
  10. import itertools
  11. import sys
  12. try:
  13. import threading
  14. except ImportError:
  15. threading = None
  16. import unittest
  17. import warnings
  18. from binascii import unhexlify
  19. from test import test_support
  20. from test.test_support import _4G, precisionbigmemtest
  21. # Were we compiled --with-pydebug or with #define Py_DEBUG?
  22. COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
  23. def hexstr(s):
  24. import string
  25. h = string.hexdigits
  26. r = ''
  27. for c in s:
  28. i = ord(c)
  29. r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
  30. return r
  31. class HashLibTestCase(unittest.TestCase):
  32. supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
  33. 'sha224', 'SHA224', 'sha256', 'SHA256',
  34. 'sha384', 'SHA384', 'sha512', 'SHA512' )
  35. _warn_on_extension_import = COMPILED_WITH_PYDEBUG
  36. def _conditional_import_module(self, module_name):
  37. """Import a module and return a reference to it or None on failure."""
  38. try:
  39. exec('import '+module_name)
  40. except ImportError, error:
  41. if self._warn_on_extension_import:
  42. warnings.warn('Did a C extension fail to compile? %s' % error)
  43. return locals().get(module_name)
  44. def __init__(self, *args, **kwargs):
  45. algorithms = set()
  46. for algorithm in self.supported_hash_names:
  47. algorithms.add(algorithm.lower())
  48. self.constructors_to_test = {}
  49. for algorithm in algorithms:
  50. self.constructors_to_test[algorithm] = set()
  51. # For each algorithm, test the direct constructor and the use
  52. # of hashlib.new given the algorithm name.
  53. for algorithm, constructors in self.constructors_to_test.items():
  54. constructors.add(getattr(hashlib, algorithm))
  55. def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
  56. if data is None:
  57. return hashlib.new(_alg)
  58. return hashlib.new(_alg, data)
  59. constructors.add(_test_algorithm_via_hashlib_new)
  60. _hashlib = self._conditional_import_module('_hashlib')
  61. if _hashlib:
  62. # These two algorithms should always be present when this module
  63. # is compiled. If not, something was compiled wrong.
  64. assert hasattr(_hashlib, 'openssl_md5')
  65. assert hasattr(_hashlib, 'openssl_sha1')
  66. for algorithm, constructors in self.constructors_to_test.items():
  67. constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
  68. if constructor:
  69. constructors.add(constructor)
  70. _md5 = self._conditional_import_module('_md5')
  71. if _md5:
  72. self.constructors_to_test['md5'].add(_md5.new)
  73. _sha = self._conditional_import_module('_sha')
  74. if _sha:
  75. self.constructors_to_test['sha1'].add(_sha.new)
  76. _sha256 = self._conditional_import_module('_sha256')
  77. if _sha256:
  78. self.constructors_to_test['sha224'].add(_sha256.sha224)
  79. self.constructors_to_test['sha256'].add(_sha256.sha256)
  80. _sha512 = self._conditional_import_module('_sha512')
  81. if _sha512:
  82. self.constructors_to_test['sha384'].add(_sha512.sha384)
  83. self.constructors_to_test['sha512'].add(_sha512.sha512)
  84. super(HashLibTestCase, self).__init__(*args, **kwargs)
  85. def test_hash_array(self):
  86. a = array.array("b", range(10))
  87. constructors = self.constructors_to_test.itervalues()
  88. for cons in itertools.chain.from_iterable(constructors):
  89. c = cons(a)
  90. c.hexdigest()
  91. def test_algorithms_attribute(self):
  92. self.assertEqual(hashlib.algorithms,
  93. tuple([_algo for _algo in self.supported_hash_names if
  94. _algo.islower()]))
  95. def test_algorithms_guaranteed(self):
  96. self.assertEqual(hashlib.algorithms_guaranteed,
  97. set(_algo for _algo in self.supported_hash_names
  98. if _algo.islower()))
  99. def test_algorithms_available(self):
  100. self.assertTrue(set(hashlib.algorithms_guaranteed).
  101. issubset(hashlib.algorithms_available))
  102. def test_unknown_hash(self):
  103. self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
  104. self.assertRaises(TypeError, hashlib.new, 1)
  105. def test_get_builtin_constructor(self):
  106. get_builtin_constructor = hashlib.__dict__[
  107. '__get_builtin_constructor']
  108. self.assertRaises(ValueError, get_builtin_constructor, 'test')
  109. try:
  110. import _md5
  111. except ImportError:
  112. pass
  113. # This forces an ImportError for "import _md5" statements
  114. sys.modules['_md5'] = None
  115. try:
  116. self.assertRaises(ValueError, get_builtin_constructor, 'md5')
  117. finally:
  118. if '_md5' in locals():
  119. sys.modules['_md5'] = _md5
  120. else:
  121. del sys.modules['_md5']
  122. self.assertRaises(TypeError, get_builtin_constructor, 3)
  123. def test_hexdigest(self):
  124. for name in self.supported_hash_names:
  125. h = hashlib.new(name)
  126. self.assertTrue(hexstr(h.digest()) == h.hexdigest())
  127. def test_large_update(self):
  128. aas = 'a' * 128
  129. bees = 'b' * 127
  130. cees = 'c' * 126
  131. abcs = aas + bees + cees
  132. for name in self.supported_hash_names:
  133. m1 = hashlib.new(name)
  134. m1.update(aas)
  135. m1.update(bees)
  136. m1.update(cees)
  137. m2 = hashlib.new(name)
  138. m2.update(abcs)
  139. self.assertEqual(m1.digest(), m2.digest(), name+' update problem.')
  140. m3 = hashlib.new(name, abcs)
  141. self.assertEqual(m1.digest(), m3.digest(), name+' new problem.')
  142. def check(self, name, data, digest):
  143. constructors = self.constructors_to_test[name]
  144. # 2 is for hashlib.name(...) and hashlib.new(name, ...)
  145. self.assertGreaterEqual(len(constructors), 2)
  146. for hash_object_constructor in constructors:
  147. computed = hash_object_constructor(data).hexdigest()
  148. self.assertEqual(
  149. computed, digest,
  150. "Hash algorithm %s constructed using %s returned hexdigest"
  151. " %r for %d byte input data that should have hashed to %r."
  152. % (name, hash_object_constructor,
  153. computed, len(data), digest))
  154. def check_update(self, name, data, digest):
  155. constructors = self.constructors_to_test[name]
  156. # 2 is for hashlib.name(...) and hashlib.new(name, ...)
  157. self.assertGreaterEqual(len(constructors), 2)
  158. for hash_object_constructor in constructors:
  159. h = hash_object_constructor()
  160. h.update(data)
  161. computed = h.hexdigest()
  162. self.assertEqual(
  163. computed, digest,
  164. "Hash algorithm %s using %s when updated returned hexdigest"
  165. " %r for %d byte input data that should have hashed to %r."
  166. % (name, hash_object_constructor,
  167. computed, len(data), digest))
  168. def check_unicode(self, algorithm_name):
  169. # Unicode objects are not allowed as input.
  170. expected = hashlib.new(algorithm_name, str(u'spam')).hexdigest()
  171. self.check(algorithm_name, u'spam', expected)
  172. def test_unicode(self):
  173. # In python 2.x unicode is auto-encoded to the system default encoding
  174. # when passed to hashlib functions.
  175. self.check_unicode('md5')
  176. self.check_unicode('sha1')
  177. self.check_unicode('sha224')
  178. self.check_unicode('sha256')
  179. self.check_unicode('sha384')
  180. self.check_unicode('sha512')
  181. def test_case_md5_0(self):
  182. self.check('md5', '', 'd41d8cd98f00b204e9800998ecf8427e')
  183. def test_case_md5_1(self):
  184. self.check('md5', 'abc', '900150983cd24fb0d6963f7d28e17f72')
  185. def test_case_md5_2(self):
  186. self.check('md5', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
  187. 'd174ab98d277d9f5a5611c2c9f419d9f')
  188. @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
  189. @precisionbigmemtest(size=_4G + 5, memuse=1, dry_run=False)
  190. def test_case_md5_huge(self, size):
  191. self.check('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
  192. @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
  193. @precisionbigmemtest(size=_4G + 5, memuse=1, dry_run=False)
  194. def test_case_md5_huge_update(self, size):
  195. self.check_update('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
  196. @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems')
  197. @precisionbigmemtest(size=_4G - 1, memuse=1, dry_run=False)
  198. def test_case_md5_uintmax(self, size):
  199. self.check('md5', 'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
  200. # use the three examples from Federal Information Processing Standards
  201. # Publication 180-1, Secure Hash Standard, 1995 April 17
  202. # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
  203. def test_case_sha1_0(self):
  204. self.check('sha1', "",
  205. "da39a3ee5e6b4b0d3255bfef95601890afd80709")
  206. def test_case_sha1_1(self):
  207. self.check('sha1', "abc",
  208. "a9993e364706816aba3e25717850c26c9cd0d89d")
  209. def test_case_sha1_2(self):
  210. self.check('sha1', "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  211. "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
  212. def test_case_sha1_3(self):
  213. self.check('sha1', "a" * 1000000,
  214. "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
  215. @precisionbigmemtest(size=_4G + 5, memuse=1)
  216. def test_case_sha1_huge(self, size):
  217. if size == _4G + 5:
  218. try:
  219. self.check('sha1', 'A'*size,
  220. '87d745c50e6b2879ffa0fb2c930e9fbfe0dc9a5b')
  221. except OverflowError:
  222. pass # 32-bit arch
  223. @precisionbigmemtest(size=_4G + 5, memuse=1)
  224. def test_case_sha1_huge_update(self, size):
  225. if size == _4G + 5:
  226. try:
  227. self.check_update('sha1', 'A'*size,
  228. '87d745c50e6b2879ffa0fb2c930e9fbfe0dc9a5b')
  229. except OverflowError:
  230. pass # 32-bit arch
  231. # use the examples from Federal Information Processing Standards
  232. # Publication 180-2, Secure Hash Standard, 2002 August 1
  233. # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
  234. def test_case_sha224_0(self):
  235. self.check('sha224', "",
  236. "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
  237. def test_case_sha224_1(self):
  238. self.check('sha224', "abc",
  239. "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
  240. def test_case_sha224_2(self):
  241. self.check('sha224',
  242. "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  243. "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
  244. def test_case_sha224_3(self):
  245. self.check('sha224', "a" * 1000000,
  246. "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
  247. def test_case_sha256_0(self):
  248. self.check('sha256', "",
  249. "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
  250. def test_case_sha256_1(self):
  251. self.check('sha256', "abc",
  252. "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
  253. def test_case_sha256_2(self):
  254. self.check('sha256',
  255. "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  256. "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
  257. def test_case_sha256_3(self):
  258. self.check('sha256', "a" * 1000000,
  259. "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
  260. def test_case_sha384_0(self):
  261. self.check('sha384', "",
  262. "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
  263. "274edebfe76f65fbd51ad2f14898b95b")
  264. def test_case_sha384_1(self):
  265. self.check('sha384', "abc",
  266. "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
  267. "8086072ba1e7cc2358baeca134c825a7")
  268. def test_case_sha384_2(self):
  269. self.check('sha384',
  270. "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
  271. "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
  272. "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
  273. "fcc7c71a557e2db966c3e9fa91746039")
  274. def test_case_sha384_3(self):
  275. self.check('sha384', "a" * 1000000,
  276. "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
  277. "07b8b3dc38ecc4ebae97ddd87f3d8985")
  278. def test_case_sha512_0(self):
  279. self.check('sha512', "",
  280. "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
  281. "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
  282. def test_case_sha512_1(self):
  283. self.check('sha512', "abc",
  284. "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
  285. "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
  286. def test_case_sha512_2(self):
  287. self.check('sha512',
  288. "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
  289. "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
  290. "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
  291. "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
  292. def test_case_sha512_3(self):
  293. self.check('sha512', "a" * 1000000,
  294. "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
  295. "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
  296. @unittest.skipUnless(threading, 'Threading required for this test.')
  297. @test_support.reap_threads
  298. def test_threaded_hashing(self):
  299. # Updating the same hash object from several threads at once
  300. # using data chunk sizes containing the same byte sequences.
  301. #
  302. # If the internal locks are working to prevent multiple
  303. # updates on the same object from running at once, the resulting
  304. # hash will be the same as doing it single threaded upfront.
  305. hasher = hashlib.sha1()
  306. num_threads = 5
  307. smallest_data = 'swineflu'
  308. data = smallest_data*200000
  309. expected_hash = hashlib.sha1(data*num_threads).hexdigest()
  310. def hash_in_chunks(chunk_size, event):
  311. index = 0
  312. while index < len(data):
  313. hasher.update(data[index:index+chunk_size])
  314. index += chunk_size
  315. event.set()
  316. events = []
  317. for threadnum in xrange(num_threads):
  318. chunk_size = len(data) // (10**threadnum)
  319. assert chunk_size > 0
  320. assert chunk_size % len(smallest_data) == 0
  321. event = threading.Event()
  322. events.append(event)
  323. threading.Thread(target=hash_in_chunks,
  324. args=(chunk_size, event)).start()
  325. for event in events:
  326. event.wait()
  327. self.assertEqual(expected_hash, hasher.hexdigest())
  328. class KDFTests(unittest.TestCase):
  329. pbkdf2_test_vectors = [
  330. (b'password', b'salt', 1, None),
  331. (b'password', b'salt', 2, None),
  332. (b'password', b'salt', 4096, None),
  333. # too slow, it takes over a minute on a fast CPU.
  334. #(b'password', b'salt', 16777216, None),
  335. (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt',
  336. 4096, -1),
  337. (b'pass\0word', b'sa\0lt', 4096, 16),
  338. ]
  339. pbkdf2_results = {
  340. "sha1": [
  341. # official test vectors from RFC 6070
  342. (unhexlify('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None),
  343. (unhexlify('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None),
  344. (unhexlify('4b007901b765489abead49d926f721d065a429c1'), None),
  345. #(unhexlify('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None),
  346. (unhexlify('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c'
  347. 'f2f07038'), 25),
  348. (unhexlify('56fa6aa75548099dcc37d7f03425e0c3'), None),],
  349. "sha256": [
  350. (unhexlify('120fb6cffcf8b32c43e7225256c4f837'
  351. 'a86548c92ccc35480805987cb70be17b'), None),
  352. (unhexlify('ae4d0c95af6b46d32d0adff928f06dd0'
  353. '2a303f8ef3c251dfd6e2d85a95474c43'), None),
  354. (unhexlify('c5e478d59288c841aa530db6845c4c8d'
  355. '962893a001ce4e11a4963873aa98134a'), None),
  356. #(unhexlify('cf81c66fe8cfc04d1f31ecb65dab4089'
  357. # 'f7f179e89b3b0bcb17ad10e3ac6eba46'), None),
  358. (unhexlify('348c89dbcbd32b2f32d814b8116e84cf2b17'
  359. '347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40),
  360. (unhexlify('89b69d0516f829893c696226650a8687'), None),],
  361. "sha512": [
  362. (unhexlify('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5'
  363. 'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f'
  364. '050235d7d68b1da55e63f73b60a57fce'), None),
  365. (unhexlify('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071'
  366. '3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82'
  367. 'be67335c77a6068e04112754f27ccf4e'), None),
  368. (unhexlify('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8'
  369. '7f6902e072f457b5143f30602641b3d55cd335988cb36b84'
  370. '376060ecd532e039b742a239434af2d5'), None),
  371. (unhexlify('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8'
  372. '68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30'
  373. '225c583a186cd82bd4daea9724a3d3b8'), 64),
  374. (unhexlify('9d9e9c4cd21fe4be24d5b8244c759665'), None),],
  375. }
  376. def test_pbkdf2_hmac(self):
  377. for digest_name, results in self.pbkdf2_results.items():
  378. for i, vector in enumerate(self.pbkdf2_test_vectors):
  379. password, salt, rounds, dklen = vector
  380. expected, overwrite_dklen = results[i]
  381. if overwrite_dklen:
  382. dklen = overwrite_dklen
  383. out = hashlib.pbkdf2_hmac(
  384. digest_name, password, salt, rounds, dklen)
  385. self.assertEqual(out, expected,
  386. (digest_name, password, salt, rounds, dklen))
  387. def test_main():
  388. test_support.run_unittest(HashLibTestCase, KDFTests)
  389. if __name__ == "__main__":
  390. test_main()