Change a variable type to avoid signed overflow; replace repeated '19999' constant...
[python.git] / Lib / test / test_hashlib.py
blobb5fee5151a5197159776df4bbd0a6ac14222b5f8
1 # Test hashlib module
3 # $Id$
5 # Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
6 # Licensed to PSF under a Contributor Agreement.
9 import array
10 import hashlib
11 import StringIO
12 import itertools
13 import sys
14 try:
15 import threading
16 except ImportError:
17 threading = None
18 import unittest
19 import warnings
20 from test import test_support
21 from test.test_support import _4G, precisionbigmemtest
23 # Were we compiled --with-pydebug or with #define Py_DEBUG?
24 COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
27 def hexstr(s):
28 import string
29 h = string.hexdigits
30 r = ''
31 for c in s:
32 i = ord(c)
33 r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
34 return r
37 class HashLibTestCase(unittest.TestCase):
38 supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
39 'sha224', 'SHA224', 'sha256', 'SHA256',
40 'sha384', 'SHA384', 'sha512', 'SHA512' )
42 _warn_on_extension_import = COMPILED_WITH_PYDEBUG
44 def _conditional_import_module(self, module_name):
45 """Import a module and return a reference to it or None on failure."""
46 try:
47 exec('import '+module_name)
48 except ImportError, error:
49 if self._warn_on_extension_import:
50 warnings.warn('Did a C extension fail to compile? %s' % error)
51 return locals().get(module_name)
53 def __init__(self, *args, **kwargs):
54 algorithms = set()
55 for algorithm in self.supported_hash_names:
56 algorithms.add(algorithm.lower())
57 self.constructors_to_test = {}
58 for algorithm in algorithms:
59 self.constructors_to_test[algorithm] = set()
61 # For each algorithm, test the direct constructor and the use
62 # of hashlib.new given the algorithm name.
63 for algorithm, constructors in self.constructors_to_test.items():
64 constructors.add(getattr(hashlib, algorithm))
65 def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
66 if data is None:
67 return hashlib.new(_alg)
68 return hashlib.new(_alg, data)
69 constructors.add(_test_algorithm_via_hashlib_new)
71 _hashlib = self._conditional_import_module('_hashlib')
72 if _hashlib:
73 # These two algorithms should always be present when this module
74 # is compiled. If not, something was compiled wrong.
75 assert hasattr(_hashlib, 'openssl_md5')
76 assert hasattr(_hashlib, 'openssl_sha1')
77 for algorithm, constructors in self.constructors_to_test.items():
78 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
79 if constructor:
80 constructors.add(constructor)
82 _md5 = self._conditional_import_module('_md5')
83 if _md5:
84 self.constructors_to_test['md5'].add(_md5.new)
85 _sha = self._conditional_import_module('_sha')
86 if _sha:
87 self.constructors_to_test['sha1'].add(_sha.new)
88 _sha256 = self._conditional_import_module('_sha256')
89 if _sha256:
90 self.constructors_to_test['sha224'].add(_sha256.sha224)
91 self.constructors_to_test['sha256'].add(_sha256.sha256)
92 _sha512 = self._conditional_import_module('_sha512')
93 if _sha512:
94 self.constructors_to_test['sha384'].add(_sha512.sha384)
95 self.constructors_to_test['sha512'].add(_sha512.sha512)
97 super(HashLibTestCase, self).__init__(*args, **kwargs)
99 def test_hash_array(self):
100 a = array.array("b", range(10))
101 constructors = self.constructors_to_test.itervalues()
102 for cons in itertools.chain.from_iterable(constructors):
103 c = cons(a)
104 c.hexdigest()
106 def test_unknown_hash(self):
107 try:
108 hashlib.new('spam spam spam spam spam')
109 except ValueError:
110 pass
111 else:
112 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())
119 def test_large_update(self):
120 aas = 'a' * 128
121 bees = 'b' * 127
122 cees = 'c' * 126
123 abcs = aas + bees + cees
125 for name in self.supported_hash_names:
126 m1 = hashlib.new(name)
127 m1.update(aas)
128 m1.update(bees)
129 m1.update(cees)
131 m2 = hashlib.new(name)
132 m2.update(abcs)
133 self.assertEqual(m1.digest(), m2.digest(), name+' update problem.')
135 m3 = hashlib.new(name, abcs)
136 self.assertEqual(m1.digest(), m3.digest(), name+' new problem.')
138 def check(self, name, data, digest):
139 constructors = self.constructors_to_test[name]
140 # 2 is for hashlib.name(...) and hashlib.new(name, ...)
141 self.assertGreaterEqual(len(constructors), 2)
142 for hash_object_constructor in constructors:
143 computed = hash_object_constructor(data).hexdigest()
144 self.assertEqual(
145 computed, digest,
146 "Hash algorithm %s constructed using %s returned hexdigest"
147 " %r for %d byte input data that should have hashed to %r."
148 % (name, hash_object_constructor,
149 computed, len(data), digest))
151 def check_unicode(self, algorithm_name):
152 # Unicode objects are not allowed as input.
153 expected = hashlib.new(algorithm_name, str(u'spam')).hexdigest()
154 self.check(algorithm_name, u'spam', expected)
156 def test_unicode(self):
157 # In python 2.x unicode is auto-encoded to the system default encoding
158 # when passed to hashlib functions.
159 self.check_unicode('md5')
160 self.check_unicode('sha1')
161 self.check_unicode('sha224')
162 self.check_unicode('sha256')
163 self.check_unicode('sha384')
164 self.check_unicode('sha512')
166 def test_case_md5_0(self):
167 self.check('md5', '', 'd41d8cd98f00b204e9800998ecf8427e')
169 def test_case_md5_1(self):
170 self.check('md5', 'abc', '900150983cd24fb0d6963f7d28e17f72')
172 def test_case_md5_2(self):
173 self.check('md5', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
174 'd174ab98d277d9f5a5611c2c9f419d9f')
176 @precisionbigmemtest(size=_4G + 5, memuse=1)
177 def test_case_md5_huge(self, size):
178 if size == _4G + 5:
179 try:
180 self.check('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
181 except OverflowError:
182 pass # 32-bit arch
184 @precisionbigmemtest(size=_4G - 1, memuse=1)
185 def test_case_md5_uintmax(self, size):
186 if size == _4G - 1:
187 try:
188 self.check('md5', 'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
189 except OverflowError:
190 pass # 32-bit arch
192 # use the three examples from Federal Information Processing Standards
193 # Publication 180-1, Secure Hash Standard, 1995 April 17
194 # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
196 def test_case_sha1_0(self):
197 self.check('sha1', "",
198 "da39a3ee5e6b4b0d3255bfef95601890afd80709")
200 def test_case_sha1_1(self):
201 self.check('sha1', "abc",
202 "a9993e364706816aba3e25717850c26c9cd0d89d")
204 def test_case_sha1_2(self):
205 self.check('sha1', "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
206 "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
208 def test_case_sha1_3(self):
209 self.check('sha1', "a" * 1000000,
210 "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
213 # use the examples from Federal Information Processing Standards
214 # Publication 180-2, Secure Hash Standard, 2002 August 1
215 # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
217 def test_case_sha224_0(self):
218 self.check('sha224', "",
219 "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
221 def test_case_sha224_1(self):
222 self.check('sha224', "abc",
223 "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
225 def test_case_sha224_2(self):
226 self.check('sha224',
227 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
228 "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
230 def test_case_sha224_3(self):
231 self.check('sha224', "a" * 1000000,
232 "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
235 def test_case_sha256_0(self):
236 self.check('sha256', "",
237 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
239 def test_case_sha256_1(self):
240 self.check('sha256', "abc",
241 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
243 def test_case_sha256_2(self):
244 self.check('sha256',
245 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
246 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
248 def test_case_sha256_3(self):
249 self.check('sha256', "a" * 1000000,
250 "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
253 def test_case_sha384_0(self):
254 self.check('sha384', "",
255 "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
256 "274edebfe76f65fbd51ad2f14898b95b")
258 def test_case_sha384_1(self):
259 self.check('sha384', "abc",
260 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
261 "8086072ba1e7cc2358baeca134c825a7")
263 def test_case_sha384_2(self):
264 self.check('sha384',
265 "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
266 "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
267 "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
268 "fcc7c71a557e2db966c3e9fa91746039")
270 def test_case_sha384_3(self):
271 self.check('sha384', "a" * 1000000,
272 "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
273 "07b8b3dc38ecc4ebae97ddd87f3d8985")
276 def test_case_sha512_0(self):
277 self.check('sha512', "",
278 "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
279 "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
281 def test_case_sha512_1(self):
282 self.check('sha512', "abc",
283 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
284 "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
286 def test_case_sha512_2(self):
287 self.check('sha512',
288 "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
289 "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
290 "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
291 "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
293 def test_case_sha512_3(self):
294 self.check('sha512', "a" * 1000000,
295 "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
296 "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
298 def test_threaded_hashing(self):
299 if not threading:
300 raise unittest.SkipTest('No threading module.')
302 # Updating the same hash object from several threads at once
303 # using data chunk sizes containing the same byte sequences.
305 # If the internal locks are working to prevent multiple
306 # updates on the same object from running at once, the resulting
307 # hash will be the same as doing it single threaded upfront.
308 hasher = hashlib.sha1()
309 num_threads = 5
310 smallest_data = 'swineflu'
311 data = smallest_data*200000
312 expected_hash = hashlib.sha1(data*num_threads).hexdigest()
314 def hash_in_chunks(chunk_size, event):
315 index = 0
316 while index < len(data):
317 hasher.update(data[index:index+chunk_size])
318 index += chunk_size
319 event.set()
321 events = []
322 for threadnum in xrange(num_threads):
323 chunk_size = len(data) // (10**threadnum)
324 assert chunk_size > 0
325 assert chunk_size % len(smallest_data) == 0
326 event = threading.Event()
327 events.append(event)
328 threading.Thread(target=hash_in_chunks,
329 args=(chunk_size, event)).start()
331 for event in events:
332 event.wait()
334 self.assertEqual(expected_hash, hasher.hexdigest())
336 @test_support.reap_threads
337 def test_main():
338 test_support.run_unittest(HashLibTestCase)
340 if __name__ == "__main__":
341 test_main()