PageRenderTime 87ms CodeModel.GetById 31ms RepoModel.GetById 8ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/test_hashlib.py

https://github.com/enricosada/IronLanguages
Python | 364 lines | 352 code | 4 blank | 8 comment | 3 complexity | 3571a67206fc3170bdd43d2318a08672 MD5 | raw file
  1. # Test hashlib module
  2. #
  3. # $Id: test_hashlib.py 80564 2010-04-27 22:59:35Z victor.stinner $
  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 test import test_support
  19. from test.test_support import _4G, precisionbigmemtest
  20. # Were we compiled --with-pydebug or with #define Py_DEBUG?
  21. COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
  22. def hexstr(s):
  23. import string
  24. h = string.hexdigits
  25. r = ''
  26. for c in s:
  27. i = ord(c)
  28. r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
  29. return r
  30. class HashLibTestCase(unittest.TestCase):
  31. supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
  32. 'sha224', 'SHA224', 'sha256', 'SHA256',
  33. 'sha384', 'SHA384', 'sha512', 'SHA512' )
  34. if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/16870"):
  35. supported_hash_names = list(supported_hash_names)
  36. supported_hash_names.remove("sha224")
  37. supported_hash_names.remove("SHA224")
  38. supported_hash_names = tuple(supported_hash_names)
  39. _warn_on_extension_import = COMPILED_WITH_PYDEBUG
  40. def _conditional_import_module(self, module_name):
  41. """Import a module and return a reference to it or None on failure."""
  42. try:
  43. exec('import '+module_name)
  44. except ImportError, error:
  45. if self._warn_on_extension_import:
  46. warnings.warn('Did a C extension fail to compile? %s' % error)
  47. return locals().get(module_name)
  48. def __init__(self, *args, **kwargs):
  49. algorithms = set()
  50. for algorithm in self.supported_hash_names:
  51. algorithms.add(algorithm.lower())
  52. self.constructors_to_test = {}
  53. for algorithm in algorithms:
  54. self.constructors_to_test[algorithm] = set()
  55. # For each algorithm, test the direct constructor and the use
  56. # of hashlib.new given the algorithm name.
  57. for algorithm, constructors in self.constructors_to_test.items():
  58. constructors.add(getattr(hashlib, algorithm))
  59. def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
  60. if data is None:
  61. return hashlib.new(_alg)
  62. return hashlib.new(_alg, data)
  63. constructors.add(_test_algorithm_via_hashlib_new)
  64. _hashlib = self._conditional_import_module('_hashlib')
  65. if _hashlib:
  66. # These two algorithms should always be present when this module
  67. # is compiled. If not, something was compiled wrong.
  68. assert hasattr(_hashlib, 'openssl_md5')
  69. assert hasattr(_hashlib, 'openssl_sha1')
  70. for algorithm, constructors in self.constructors_to_test.items():
  71. constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
  72. if constructor:
  73. constructors.add(constructor)
  74. _md5 = self._conditional_import_module('_md5')
  75. if _md5:
  76. self.constructors_to_test['md5'].add(_md5.new)
  77. _sha = self._conditional_import_module('_sha')
  78. if _sha:
  79. self.constructors_to_test['sha1'].add(_sha.new)
  80. _sha256 = self._conditional_import_module('_sha256')
  81. if _sha256:
  82. if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/16870"):
  83. self.constructors_to_test['sha224'].add(_sha256.sha224)
  84. self.constructors_to_test['sha256'].add(_sha256.sha256)
  85. _sha512 = self._conditional_import_module('_sha512')
  86. if _sha512:
  87. self.constructors_to_test['sha384'].add(_sha512.sha384)
  88. self.constructors_to_test['sha512'].add(_sha512.sha512)
  89. super(HashLibTestCase, self).__init__(*args, **kwargs)
  90. @unittest.skipIf(test_support.is_cli, "http://ironpython.codeplex.com/workitem/28171")
  91. def test_hash_array(self):
  92. a = array.array("b", range(10))
  93. constructors = self.constructors_to_test.itervalues()
  94. for cons in itertools.chain.from_iterable(constructors):
  95. c = cons(a)
  96. c.hexdigest()
  97. def test_algorithms_attribute(self):
  98. if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/16870"):
  99. self.assertEqual(set(hashlib.algorithms),
  100. set([_algo for _algo in self.supported_hash_names if
  101. _algo.islower()] +
  102. ['sha224']))
  103. else:
  104. self.assertEqual(hashlib.algorithms,
  105. tuple([_algo for _algo in self.supported_hash_names if
  106. _algo.islower()]))
  107. def test_unknown_hash(self):
  108. try:
  109. hashlib.new('spam spam spam spam spam')
  110. except ValueError:
  111. pass
  112. else:
  113. self.assertTrue(0 == "hashlib didn't reject bogus hash name")
  114. def test_hexdigest(self):
  115. for name in self.supported_hash_names:
  116. h = hashlib.new(name)
  117. self.assertTrue(hexstr(h.digest()) == h.hexdigest())
  118. def test_large_update(self):
  119. aas = 'a' * 128
  120. bees = 'b' * 127
  121. cees = 'c' * 126
  122. abcs = aas + bees + cees
  123. for name in self.supported_hash_names:
  124. m1 = hashlib.new(name)
  125. m1.update(aas)
  126. m1.update(bees)
  127. m1.update(cees)
  128. m2 = hashlib.new(name)
  129. m2.update(abcs)
  130. self.assertEqual(m1.digest(), m2.digest(), name+' update problem.')
  131. m3 = hashlib.new(name, abcs)
  132. self.assertEqual(m1.digest(), m3.digest(), name+' new problem.')
  133. def check(self, name, data, digest):
  134. constructors = self.constructors_to_test[name]
  135. # 2 is for hashlib.name(...) and hashlib.new(name, ...)
  136. self.assertGreaterEqual(len(constructors), 2)
  137. for hash_object_constructor in constructors:
  138. computed = hash_object_constructor(data).hexdigest()
  139. self.assertEqual(
  140. computed, digest,
  141. "Hash algorithm %s constructed using %s returned hexdigest"
  142. " %r for %d byte input data that should have hashed to %r."
  143. % (name, hash_object_constructor,
  144. computed, len(data), digest))
  145. def check_unicode(self, algorithm_name):
  146. # Unicode objects are not allowed as input.
  147. expected = hashlib.new(algorithm_name, str(u'spam')).hexdigest()
  148. self.check(algorithm_name, u'spam', expected)
  149. def test_unicode(self):
  150. # In python 2.x unicode is auto-encoded to the system default encoding
  151. # when passed to hashlib functions.
  152. self.check_unicode('md5')
  153. self.check_unicode('sha1')
  154. if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/16870"):
  155. self.check_unicode('sha224')
  156. self.check_unicode('sha256')
  157. self.check_unicode('sha384')
  158. self.check_unicode('sha512')
  159. def test_case_md5_0(self):
  160. self.check('md5', '', 'd41d8cd98f00b204e9800998ecf8427e')
  161. def test_case_md5_1(self):
  162. self.check('md5', 'abc', '900150983cd24fb0d6963f7d28e17f72')
  163. def test_case_md5_2(self):
  164. self.check('md5', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
  165. 'd174ab98d277d9f5a5611c2c9f419d9f')
  166. @precisionbigmemtest(size=_4G + 5, memuse=1)
  167. def test_case_md5_huge(self, size):
  168. if size == _4G + 5:
  169. try:
  170. self.check('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
  171. except OverflowError:
  172. pass # 32-bit arch
  173. @precisionbigmemtest(size=_4G - 1, memuse=1)
  174. def test_case_md5_uintmax(self, size):
  175. if size == _4G - 1:
  176. try:
  177. self.check('md5', 'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
  178. except OverflowError:
  179. pass # 32-bit arch
  180. # use the three examples from Federal Information Processing Standards
  181. # Publication 180-1, Secure Hash Standard, 1995 April 17
  182. # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
  183. def test_case_sha1_0(self):
  184. self.check('sha1', "",
  185. "da39a3ee5e6b4b0d3255bfef95601890afd80709")
  186. def test_case_sha1_1(self):
  187. self.check('sha1', "abc",
  188. "a9993e364706816aba3e25717850c26c9cd0d89d")
  189. def test_case_sha1_2(self):
  190. self.check('sha1', "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  191. "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
  192. def test_case_sha1_3(self):
  193. self.check('sha1', "a" * 1000000,
  194. "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
  195. # use the examples from Federal Information Processing Standards
  196. # Publication 180-2, Secure Hash Standard, 2002 August 1
  197. # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
  198. @unittest.skipIf(test_support.is_cli, "http://ironpython.codeplex.com/workitem/16870")
  199. def test_case_sha224_0(self):
  200. self.check('sha224', "",
  201. "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
  202. @unittest.skipIf(test_support.is_cli, "http://ironpython.codeplex.com/workitem/16870")
  203. def test_case_sha224_1(self):
  204. self.check('sha224', "abc",
  205. "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
  206. @unittest.skipIf(test_support.is_cli, "http://ironpython.codeplex.com/workitem/16870")
  207. def test_case_sha224_2(self):
  208. self.check('sha224',
  209. "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  210. "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
  211. @unittest.skipIf(test_support.is_cli, "http://ironpython.codeplex.com/workitem/16870")
  212. def test_case_sha224_3(self):
  213. self.check('sha224', "a" * 1000000,
  214. "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
  215. def test_case_sha256_0(self):
  216. self.check('sha256', "",
  217. "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
  218. def test_case_sha256_1(self):
  219. self.check('sha256', "abc",
  220. "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
  221. def test_case_sha256_2(self):
  222. self.check('sha256',
  223. "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  224. "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
  225. def test_case_sha256_3(self):
  226. self.check('sha256', "a" * 1000000,
  227. "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
  228. def test_case_sha384_0(self):
  229. self.check('sha384', "",
  230. "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
  231. "274edebfe76f65fbd51ad2f14898b95b")
  232. def test_case_sha384_1(self):
  233. self.check('sha384', "abc",
  234. "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
  235. "8086072ba1e7cc2358baeca134c825a7")
  236. def test_case_sha384_2(self):
  237. self.check('sha384',
  238. "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
  239. "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
  240. "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
  241. "fcc7c71a557e2db966c3e9fa91746039")
  242. def test_case_sha384_3(self):
  243. self.check('sha384', "a" * 1000000,
  244. "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
  245. "07b8b3dc38ecc4ebae97ddd87f3d8985")
  246. def test_case_sha512_0(self):
  247. self.check('sha512', "",
  248. "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
  249. "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
  250. def test_case_sha512_1(self):
  251. self.check('sha512', "abc",
  252. "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
  253. "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
  254. def test_case_sha512_2(self):
  255. self.check('sha512',
  256. "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
  257. "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
  258. "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
  259. "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
  260. def test_case_sha512_3(self):
  261. self.check('sha512', "a" * 1000000,
  262. "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
  263. "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
  264. @unittest.skipIf(sys.platform == 'cli', 'Deadlock on IronPython')
  265. @unittest.skipUnless(threading, 'Threading required for this test.')
  266. @unittest.skipIf(test_support.is_cli, "hangs on CLR: http://ironpython.codeplex.com/workitem/28171")
  267. @test_support.reap_threads
  268. def test_threaded_hashing(self):
  269. # Updating the same hash object from several threads at once
  270. # using data chunk sizes containing the same byte sequences.
  271. #
  272. # If the internal locks are working to prevent multiple
  273. # updates on the same object from running at once, the resulting
  274. # hash will be the same as doing it single threaded upfront.
  275. hasher = hashlib.sha1()
  276. num_threads = 5
  277. smallest_data = 'swineflu'
  278. data = smallest_data*200000
  279. expected_hash = hashlib.sha1(data*num_threads).hexdigest()
  280. def hash_in_chunks(chunk_size, event):
  281. index = 0
  282. while index < len(data):
  283. hasher.update(data[index:index+chunk_size])
  284. index += chunk_size
  285. event.set()
  286. events = []
  287. for threadnum in xrange(num_threads):
  288. chunk_size = len(data) // (10**threadnum)
  289. assert chunk_size > 0
  290. assert chunk_size % len(smallest_data) == 0
  291. event = threading.Event()
  292. events.append(event)
  293. threading.Thread(target=hash_in_chunks,
  294. args=(chunk_size, event)).start()
  295. for event in events:
  296. event.wait()
  297. self.assertEqual(expected_hash, hasher.hexdigest())
  298. def test_main():
  299. test_support.run_unittest(HashLibTestCase)
  300. if __name__ == "__main__":
  301. test_main()