blob: f5c242e6c9da6f2461a01df31b74b0f3f4bda461 [file] [log] [blame]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001# Test hashlib module
2#
3# $Id$
4#
Georg Brandl8cdc9bc2010-01-01 13:07:05 +00005# Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00006# Licensed to PSF under a Contributor Agreement.
7#
8
Benjamin Peterson2b6e4bc2010-01-05 00:04:19 +00009import array
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000010import hashlib
Benjamin Peterson2b6e4bc2010-01-05 00:04:19 +000011import itertools
Gregory P. Smith6dcdcde2010-01-03 00:19:04 +000012import sys
Gregory P. Smithd02eeda2009-05-04 00:16:49 +000013try:
14 import threading
15except ImportError:
16 threading = None
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000017import unittest
Gregory P. Smith6dcdcde2010-01-03 00:19:04 +000018import warnings
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000019from test import test_support
Benjamin Peterson8c2b7dc2008-09-18 01:22:16 +000020from test.test_support import _4G, precisionbigmemtest
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000021
Gregory P. Smith6dcdcde2010-01-03 00:19:04 +000022# Were we compiled --with-pydebug or with #define Py_DEBUG?
23COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
24
25
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000026def hexstr(s):
27 import string
28 h = string.hexdigits
29 r = ''
30 for c in s:
31 i = ord(c)
32 r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
33 return r
34
35
36class HashLibTestCase(unittest.TestCase):
37 supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
38 'sha224', 'SHA224', 'sha256', 'SHA256',
39 'sha384', 'SHA384', 'sha512', 'SHA512' )
40
Gregory P. Smith6dcdcde2010-01-03 00:19:04 +000041 _warn_on_extension_import = COMPILED_WITH_PYDEBUG
42
43 def _conditional_import_module(self, module_name):
44 """Import a module and return a reference to it or None on failure."""
45 try:
46 exec('import '+module_name)
47 except ImportError, error:
48 if self._warn_on_extension_import:
49 warnings.warn('Did a C extension fail to compile? %s' % error)
50 return locals().get(module_name)
51
52 def __init__(self, *args, **kwargs):
53 algorithms = set()
54 for algorithm in self.supported_hash_names:
55 algorithms.add(algorithm.lower())
56 self.constructors_to_test = {}
57 for algorithm in algorithms:
58 self.constructors_to_test[algorithm] = set()
59
60 # For each algorithm, test the direct constructor and the use
61 # of hashlib.new given the algorithm name.
62 for algorithm, constructors in self.constructors_to_test.items():
63 constructors.add(getattr(hashlib, algorithm))
64 def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
65 if data is None:
66 return hashlib.new(_alg)
67 return hashlib.new(_alg, data)
68 constructors.add(_test_algorithm_via_hashlib_new)
69
70 _hashlib = self._conditional_import_module('_hashlib')
71 if _hashlib:
72 # These two algorithms should always be present when this module
73 # is compiled. If not, something was compiled wrong.
74 assert hasattr(_hashlib, 'openssl_md5')
75 assert hasattr(_hashlib, 'openssl_sha1')
76 for algorithm, constructors in self.constructors_to_test.items():
77 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
78 if constructor:
79 constructors.add(constructor)
80
81 _md5 = self._conditional_import_module('_md5')
82 if _md5:
83 self.constructors_to_test['md5'].add(_md5.new)
84 _sha = self._conditional_import_module('_sha')
85 if _sha:
86 self.constructors_to_test['sha1'].add(_sha.new)
87 _sha256 = self._conditional_import_module('_sha256')
88 if _sha256:
89 self.constructors_to_test['sha224'].add(_sha256.sha224)
90 self.constructors_to_test['sha256'].add(_sha256.sha256)
91 _sha512 = self._conditional_import_module('_sha512')
92 if _sha512:
93 self.constructors_to_test['sha384'].add(_sha512.sha384)
94 self.constructors_to_test['sha512'].add(_sha512.sha512)
95
96 super(HashLibTestCase, self).__init__(*args, **kwargs)
97
Benjamin Peterson2b6e4bc2010-01-05 00:04:19 +000098 def test_hash_array(self):
99 a = array.array("b", range(10))
100 constructors = self.constructors_to_test.itervalues()
101 for cons in itertools.chain.from_iterable(constructors):
102 c = cons(a)
103 c.hexdigest()
104
Gregory P. Smithe6390a12010-03-01 02:01:47 +0000105 def test_algorithms_attribute(self):
106 self.assertEqual(hashlib.algorithms,
107 tuple([_algo for _algo in self.supported_hash_names if
108 _algo.islower()]))
109
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000110 def test_unknown_hash(self):
Amaury Forgeot d'Arcd958cc92012-06-29 01:42:46 +0200111 self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
112 self.assertRaises(TypeError, hashlib.new, 1)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000113
Gregory P. Smithfb1d60c2011-05-14 15:07:53 -0700114 def test_get_builtin_constructor(self):
115 get_builtin_constructor = hashlib.__dict__[
116 '__get_builtin_constructor']
117 self.assertRaises(ValueError, get_builtin_constructor, 'test')
118 try:
119 import _md5
120 except ImportError:
121 pass
122 # This forces an ImportError for "import _md5" statements
123 sys.modules['_md5'] = None
124 try:
125 self.assertRaises(ValueError, get_builtin_constructor, 'md5')
126 finally:
127 if '_md5' in locals():
128 sys.modules['_md5'] = _md5
129 else:
130 del sys.modules['_md5']
Gregory P. Smithb9e9e0d2012-07-21 21:22:16 -0700131 self.assertRaises(TypeError, get_builtin_constructor, 3)
Gregory P. Smithfb1d60c2011-05-14 15:07:53 -0700132
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000133 def test_hexdigest(self):
134 for name in self.supported_hash_names:
135 h = hashlib.new(name)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000136 self.assertTrue(hexstr(h.digest()) == h.hexdigest())
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000137
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000138 def test_large_update(self):
139 aas = 'a' * 128
140 bees = 'b' * 127
141 cees = 'c' * 126
Gregory P. Smithea388262009-02-13 03:00:00 +0000142 abcs = aas + bees + cees
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000143
144 for name in self.supported_hash_names:
145 m1 = hashlib.new(name)
146 m1.update(aas)
147 m1.update(bees)
148 m1.update(cees)
149
150 m2 = hashlib.new(name)
Gregory P. Smithea388262009-02-13 03:00:00 +0000151 m2.update(abcs)
152 self.assertEqual(m1.digest(), m2.digest(), name+' update problem.')
153
154 m3 = hashlib.new(name, abcs)
155 self.assertEqual(m1.digest(), m3.digest(), name+' new problem.')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000156
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000157 def check(self, name, data, digest):
Gregory P. Smith6dcdcde2010-01-03 00:19:04 +0000158 constructors = self.constructors_to_test[name]
159 # 2 is for hashlib.name(...) and hashlib.new(name, ...)
160 self.assertGreaterEqual(len(constructors), 2)
161 for hash_object_constructor in constructors:
162 computed = hash_object_constructor(data).hexdigest()
163 self.assertEqual(
164 computed, digest,
165 "Hash algorithm %s constructed using %s returned hexdigest"
166 " %r for %d byte input data that should have hashed to %r."
167 % (name, hash_object_constructor,
168 computed, len(data), digest))
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000169
Gregory P. Smith443ec682010-01-02 22:28:48 +0000170 def check_unicode(self, algorithm_name):
Gregory P. Smithea388262009-02-13 03:00:00 +0000171 # Unicode objects are not allowed as input.
Gregory P. Smith443ec682010-01-02 22:28:48 +0000172 expected = hashlib.new(algorithm_name, str(u'spam')).hexdigest()
Gregory P. Smith6dcdcde2010-01-03 00:19:04 +0000173 self.check(algorithm_name, u'spam', expected)
Gregory P. Smithea388262009-02-13 03:00:00 +0000174
Gregory P. Smith443ec682010-01-02 22:28:48 +0000175 def test_unicode(self):
176 # In python 2.x unicode is auto-encoded to the system default encoding
177 # when passed to hashlib functions.
178 self.check_unicode('md5')
179 self.check_unicode('sha1')
180 self.check_unicode('sha224')
181 self.check_unicode('sha256')
182 self.check_unicode('sha384')
183 self.check_unicode('sha512')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000184
185 def test_case_md5_0(self):
186 self.check('md5', '', 'd41d8cd98f00b204e9800998ecf8427e')
187
188 def test_case_md5_1(self):
189 self.check('md5', 'abc', '900150983cd24fb0d6963f7d28e17f72')
190
191 def test_case_md5_2(self):
192 self.check('md5', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
193 'd174ab98d277d9f5a5611c2c9f419d9f')
194
Benjamin Peterson8c2b7dc2008-09-18 01:22:16 +0000195 @precisionbigmemtest(size=_4G + 5, memuse=1)
196 def test_case_md5_huge(self, size):
197 if size == _4G + 5:
198 try:
199 self.check('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
200 except OverflowError:
201 pass # 32-bit arch
202
203 @precisionbigmemtest(size=_4G - 1, memuse=1)
204 def test_case_md5_uintmax(self, size):
205 if size == _4G - 1:
206 try:
207 self.check('md5', 'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
208 except OverflowError:
209 pass # 32-bit arch
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000210
211 # use the three examples from Federal Information Processing Standards
212 # Publication 180-1, Secure Hash Standard, 1995 April 17
213 # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
214
215 def test_case_sha1_0(self):
216 self.check('sha1', "",
217 "da39a3ee5e6b4b0d3255bfef95601890afd80709")
218
219 def test_case_sha1_1(self):
220 self.check('sha1', "abc",
221 "a9993e364706816aba3e25717850c26c9cd0d89d")
222
223 def test_case_sha1_2(self):
224 self.check('sha1', "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
225 "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
226
227 def test_case_sha1_3(self):
228 self.check('sha1', "a" * 1000000,
229 "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
230
231
232 # use the examples from Federal Information Processing Standards
233 # Publication 180-2, Secure Hash Standard, 2002 August 1
234 # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
235
236 def test_case_sha224_0(self):
237 self.check('sha224', "",
238 "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
239
240 def test_case_sha224_1(self):
241 self.check('sha224', "abc",
242 "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
243
244 def test_case_sha224_2(self):
245 self.check('sha224',
246 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
247 "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
248
249 def test_case_sha224_3(self):
250 self.check('sha224', "a" * 1000000,
251 "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
252
253
254 def test_case_sha256_0(self):
255 self.check('sha256', "",
256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
257
258 def test_case_sha256_1(self):
259 self.check('sha256', "abc",
260 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
261
262 def test_case_sha256_2(self):
263 self.check('sha256',
264 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
265 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
266
267 def test_case_sha256_3(self):
268 self.check('sha256', "a" * 1000000,
269 "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
270
271
272 def test_case_sha384_0(self):
273 self.check('sha384', "",
274 "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
275 "274edebfe76f65fbd51ad2f14898b95b")
276
277 def test_case_sha384_1(self):
278 self.check('sha384', "abc",
279 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
280 "8086072ba1e7cc2358baeca134c825a7")
281
282 def test_case_sha384_2(self):
283 self.check('sha384',
284 "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
285 "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
286 "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
287 "fcc7c71a557e2db966c3e9fa91746039")
288
289 def test_case_sha384_3(self):
290 self.check('sha384', "a" * 1000000,
291 "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
292 "07b8b3dc38ecc4ebae97ddd87f3d8985")
293
294
295 def test_case_sha512_0(self):
296 self.check('sha512', "",
297 "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
298 "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
299
300 def test_case_sha512_1(self):
301 self.check('sha512', "abc",
302 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
303 "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
304
305 def test_case_sha512_2(self):
306 self.check('sha512',
307 "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
308 "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
309 "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
310 "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
311
312 def test_case_sha512_3(self):
313 self.check('sha512', "a" * 1000000,
314 "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
315 "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
316
Victor Stinnerfd8ea992010-04-27 22:59:35 +0000317 @unittest.skipUnless(threading, 'Threading required for this test.')
318 @test_support.reap_threads
Gregory P. Smithd02eeda2009-05-04 00:16:49 +0000319 def test_threaded_hashing(self):
Gregory P. Smithd02eeda2009-05-04 00:16:49 +0000320 # Updating the same hash object from several threads at once
321 # using data chunk sizes containing the same byte sequences.
322 #
323 # If the internal locks are working to prevent multiple
324 # updates on the same object from running at once, the resulting
325 # hash will be the same as doing it single threaded upfront.
326 hasher = hashlib.sha1()
327 num_threads = 5
328 smallest_data = 'swineflu'
329 data = smallest_data*200000
330 expected_hash = hashlib.sha1(data*num_threads).hexdigest()
331
332 def hash_in_chunks(chunk_size, event):
333 index = 0
334 while index < len(data):
335 hasher.update(data[index:index+chunk_size])
336 index += chunk_size
337 event.set()
338
339 events = []
340 for threadnum in xrange(num_threads):
341 chunk_size = len(data) // (10**threadnum)
342 assert chunk_size > 0
343 assert chunk_size % len(smallest_data) == 0
344 event = threading.Event()
345 events.append(event)
346 threading.Thread(target=hash_in_chunks,
347 args=(chunk_size, event)).start()
348
349 for event in events:
350 event.wait()
351
352 self.assertEqual(expected_hash, hasher.hexdigest())
353
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000354def test_main():
Benjamin Peterson0db3cd62009-05-14 22:40:34 +0000355 test_support.run_unittest(HashLibTestCase)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000356
357if __name__ == "__main__":
358 test_main()