blob: 9f702e96f193636ca8db3d643f1d37949184de8d [file] [log] [blame]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001# Test hashlib module
2#
3# $Id$
4#
Gregory P. Smith3f61d612009-05-04 00:45:33 +00005# Copyright (C) 2005-2009 Gregory P. Smith (greg@krypto.org)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00006# Licensed to PSF under a Contributor Agreement.
7#
8
9import hashlib
Gregory P. Smith3f61d612009-05-04 00:45:33 +000010from io import StringIO
Gregory P. Smithcd54e542010-01-03 00:29:15 +000011import sys
Gregory P. Smith3f61d612009-05-04 00:45:33 +000012try:
13 import threading
14except ImportError:
15 threading = None
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000016import unittest
Gregory P. Smithcd54e542010-01-03 00:29:15 +000017import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000018from test import support
Benjamin Peterson78cb4912008-09-24 22:53:33 +000019from test.support import _4G, precisionbigmemtest
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000020
Gregory P. Smithcd54e542010-01-03 00:29:15 +000021# Were we compiled --with-pydebug or with #define Py_DEBUG?
22COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
23
24
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000025def hexstr(s):
Guido van Rossum5ed033b2007-07-09 14:29:40 +000026 assert isinstance(s, bytes), repr(s)
Guido van Rossum558ca842007-07-10 20:31:05 +000027 h = "0123456789abcdef"
28 r = ''
Guido van Rossum5ed033b2007-07-09 14:29:40 +000029 for i in s:
Guido van Rossum558ca842007-07-10 20:31:05 +000030 r += h[(i >> 4) & 0xF] + h[i & 0xF]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000031 return r
32
33
34class HashLibTestCase(unittest.TestCase):
35 supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
36 'sha224', 'SHA224', 'sha256', 'SHA256',
37 'sha384', 'SHA384', 'sha512', 'SHA512' )
38
Gregory P. Smithcd54e542010-01-03 00:29:15 +000039 _warn_on_extension_import = COMPILED_WITH_PYDEBUG
40
41 def _conditional_import_module(self, module_name):
42 """Import a module and return a reference to it or None on failure."""
43 try:
44 exec('import '+module_name)
45 except ImportError as error:
46 if self._warn_on_extension_import:
47 warnings.warn('Did a C extension fail to compile? %s' % error)
48 return locals().get(module_name)
49
50 def __init__(self, *args, **kwargs):
51 algorithms = set()
52 for algorithm in self.supported_hash_names:
53 algorithms.add(algorithm.lower())
54 self.constructors_to_test = {}
55 for algorithm in algorithms:
56 self.constructors_to_test[algorithm] = set()
57
58 # For each algorithm, test the direct constructor and the use
59 # of hashlib.new given the algorithm name.
60 for algorithm, constructors in self.constructors_to_test.items():
61 constructors.add(getattr(hashlib, algorithm))
62 def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
63 if data is None:
64 return hashlib.new(_alg)
65 return hashlib.new(_alg, data)
66 constructors.add(_test_algorithm_via_hashlib_new)
67
68 _hashlib = self._conditional_import_module('_hashlib')
69 if _hashlib:
70 # These two algorithms should always be present when this module
71 # is compiled. If not, something was compiled wrong.
72 assert hasattr(_hashlib, 'openssl_md5')
73 assert hasattr(_hashlib, 'openssl_sha1')
74 for algorithm, constructors in self.constructors_to_test.items():
75 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
76 if constructor:
77 constructors.add(constructor)
78
79 _md5 = self._conditional_import_module('_md5')
80 if _md5:
81 self.constructors_to_test['md5'].add(_md5.new)
82 _sha = self._conditional_import_module('_sha')
83 if _sha:
84 self.constructors_to_test['sha1'].add(_sha.new)
85 _sha256 = self._conditional_import_module('_sha256')
86 if _sha256:
87 self.constructors_to_test['sha224'].add(_sha256.sha224)
88 self.constructors_to_test['sha256'].add(_sha256.sha256)
89 _sha512 = self._conditional_import_module('_sha512')
90 if _sha512:
91 self.constructors_to_test['sha384'].add(_sha512.sha384)
92 self.constructors_to_test['sha512'].add(_sha512.sha512)
93
94 super(HashLibTestCase, self).__init__(*args, **kwargs)
95
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000096 def test_unknown_hash(self):
97 try:
98 hashlib.new('spam spam spam spam spam')
99 except ValueError:
100 pass
101 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000102 self.assertTrue(0 == "hashlib didn't reject bogus hash name")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000103
104 def test_hexdigest(self):
105 for name in self.supported_hash_names:
106 h = hashlib.new(name)
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000107 assert isinstance(h.digest(), bytes), name
108 self.assertEqual(hexstr(h.digest()), h.hexdigest())
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000109
110
111 def test_large_update(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000112 aas = b'a' * 128
113 bees = b'b' * 127
114 cees = b'c' * 126
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000115
116 for name in self.supported_hash_names:
117 m1 = hashlib.new(name)
118 m1.update(aas)
119 m1.update(bees)
120 m1.update(cees)
121
122 m2 = hashlib.new(name)
123 m2.update(aas + bees + cees)
124 self.assertEqual(m1.digest(), m2.digest())
125
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000126 def check(self, name, data, digest):
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000127 constructors = self.constructors_to_test[name]
128 # 2 is for hashlib.name(...) and hashlib.new(name, ...)
129 self.assertGreaterEqual(len(constructors), 2)
130 for hash_object_constructor in constructors:
131 computed = hash_object_constructor(data).hexdigest()
132 self.assertEqual(
133 computed, digest,
134 "Hash algorithm %s constructed using %s returned hexdigest"
135 " %r for %d byte input data that should have hashed to %r."
136 % (name, hash_object_constructor,
137 computed, len(data), digest))
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000138
Gregory P. Smith365a1862009-02-12 07:35:29 +0000139 def check_no_unicode(self, algorithm_name):
140 # Unicode objects are not allowed as input.
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000141 constructors = self.constructors_to_test[algorithm_name]
142 for hash_object_constructor in constructors:
143 self.assertRaises(TypeError, hash_object_constructor, 'spam')
Gregory P. Smith365a1862009-02-12 07:35:29 +0000144
145 def test_no_unicode(self):
146 self.check_no_unicode('md5')
147 self.check_no_unicode('sha1')
148 self.check_no_unicode('sha224')
149 self.check_no_unicode('sha256')
150 self.check_no_unicode('sha384')
151 self.check_no_unicode('sha512')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000152
153 def test_case_md5_0(self):
Guido van Rossum558ca842007-07-10 20:31:05 +0000154 self.check('md5', b'', 'd41d8cd98f00b204e9800998ecf8427e')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000155
156 def test_case_md5_1(self):
Guido van Rossum558ca842007-07-10 20:31:05 +0000157 self.check('md5', b'abc', '900150983cd24fb0d6963f7d28e17f72')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000158
159 def test_case_md5_2(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000160 self.check('md5',
161 b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
Guido van Rossum558ca842007-07-10 20:31:05 +0000162 'd174ab98d277d9f5a5611c2c9f419d9f')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000163
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000164 @precisionbigmemtest(size=_4G + 5, memuse=1)
165 def test_case_md5_huge(self, size):
166 if size == _4G + 5:
167 try:
168 self.check('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
169 except OverflowError:
170 pass # 32-bit arch
171
172 @precisionbigmemtest(size=_4G - 1, memuse=1)
173 def test_case_md5_uintmax(self, size):
174 if size == _4G - 1:
175 try:
176 self.check('md5', 'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
177 except OverflowError:
178 pass # 32-bit arch
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000179
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
184 def test_case_sha1_0(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000185 self.check('sha1', b"",
Guido van Rossum558ca842007-07-10 20:31:05 +0000186 "da39a3ee5e6b4b0d3255bfef95601890afd80709")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000187
188 def test_case_sha1_1(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000189 self.check('sha1', b"abc",
Guido van Rossum558ca842007-07-10 20:31:05 +0000190 "a9993e364706816aba3e25717850c26c9cd0d89d")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000191
192 def test_case_sha1_2(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000193 self.check('sha1',
194 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Guido van Rossum558ca842007-07-10 20:31:05 +0000195 "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000196
197 def test_case_sha1_3(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000198 self.check('sha1', b"a" * 1000000,
Guido van Rossum558ca842007-07-10 20:31:05 +0000199 "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000200
201
202 # use the examples from Federal Information Processing Standards
203 # Publication 180-2, Secure Hash Standard, 2002 August 1
204 # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
205
206 def test_case_sha224_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000207 self.check('sha224', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000208 "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
209
210 def test_case_sha224_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000211 self.check('sha224', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000212 "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
213
214 def test_case_sha224_2(self):
215 self.check('sha224',
Guido van Rossume22905a2007-08-27 23:09:25 +0000216 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000217 "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
218
219 def test_case_sha224_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000220 self.check('sha224', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000221 "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
222
223
224 def test_case_sha256_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000225 self.check('sha256', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000226 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
227
228 def test_case_sha256_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000229 self.check('sha256', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000230 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
231
232 def test_case_sha256_2(self):
233 self.check('sha256',
Guido van Rossume22905a2007-08-27 23:09:25 +0000234 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000235 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
236
237 def test_case_sha256_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000238 self.check('sha256', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000239 "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
240
241
242 def test_case_sha384_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000243 self.check('sha384', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000244 "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
245 "274edebfe76f65fbd51ad2f14898b95b")
246
247 def test_case_sha384_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000248 self.check('sha384', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000249 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
250 "8086072ba1e7cc2358baeca134c825a7")
251
252 def test_case_sha384_2(self):
253 self.check('sha384',
Guido van Rossume22905a2007-08-27 23:09:25 +0000254 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
255 b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000256 "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
257 "fcc7c71a557e2db966c3e9fa91746039")
258
259 def test_case_sha384_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000260 self.check('sha384', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000261 "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
262 "07b8b3dc38ecc4ebae97ddd87f3d8985")
263
264
265 def test_case_sha512_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000266 self.check('sha512', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000267 "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
268 "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
269
270 def test_case_sha512_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000271 self.check('sha512', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000272 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
273 "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
274
275 def test_case_sha512_2(self):
276 self.check('sha512',
Guido van Rossume22905a2007-08-27 23:09:25 +0000277 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
278 b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000279 "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
280 "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
281
282 def test_case_sha512_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000283 self.check('sha512', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000284 "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
285 "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
286
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000287 def test_gil(self):
288 # Check things work fine with an input larger than the size required
289 # for multithreaded operation (which is hardwired to 2048).
290 gil_minsize = 2048
291
292 m = hashlib.md5()
293 m.update(b'1')
294 m.update(b'#' * gil_minsize)
295 m.update(b'1')
296 self.assertEquals(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21')
297
298 m = hashlib.md5(b'x' * gil_minsize)
299 self.assertEquals(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000300
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000301 def test_threaded_hashing(self):
302 if not threading:
303 raise unittest.SkipTest('No threading module.')
304
305 # Updating the same hash object from several threads at once
306 # using data chunk sizes containing the same byte sequences.
307 #
308 # If the internal locks are working to prevent multiple
309 # updates on the same object from running at once, the resulting
310 # hash will be the same as doing it single threaded upfront.
311 hasher = hashlib.sha1()
312 num_threads = 5
313 smallest_data = b'swineflu'
314 data = smallest_data*200000
315 expected_hash = hashlib.sha1(data*num_threads).hexdigest()
316
317 def hash_in_chunks(chunk_size, event):
318 index = 0
319 while index < len(data):
320 hasher.update(data[index:index+chunk_size])
321 index += chunk_size
322 event.set()
323
324 events = []
325 for threadnum in range(num_threads):
326 chunk_size = len(data) // (10**threadnum)
327 assert chunk_size > 0
328 assert chunk_size % len(smallest_data) == 0
329 event = threading.Event()
330 events.append(event)
331 threading.Thread(target=hash_in_chunks,
332 args=(chunk_size, event)).start()
333
334 for event in events:
335 event.wait()
336
337 self.assertEqual(expected_hash, hasher.hexdigest())
338
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000339@support.reap_threads
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000340def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000341 support.run_unittest(HashLibTestCase)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000342
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000343if __name__ == "__main__":
344 test_main()