blob: e6df09cbf654581f0ecab571918c0ee82f434187 [file] [log] [blame]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001# Test hashlib module
2#
3# $Id$
4#
Benjamin Peterson46a99002010-01-09 18:45:30 +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 Petersona28e7022010-01-09 18:53:06 +00009import array
Christian Heimes39093e92016-09-06 20:22:28 +020010from binascii import unhexlify
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000011import hashlib
Benjamin Petersona28e7022010-01-09 18:53:06 +000012import itertools
Antoine Pitrou019ff192012-05-16 16:41:26 +020013import os
Gregory P. Smithcd54e542010-01-03 00:29:15 +000014import sys
Gregory P. Smith3f61d612009-05-04 00:45:33 +000015try:
16 import threading
17except ImportError:
18 threading = None
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000019import unittest
Gregory P. Smithcd54e542010-01-03 00:29:15 +000020import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021from test import support
Christian Heimes3626a502013-10-19 14:12:02 +020022from test.support import _4G, bigmemtest, import_fresh_module
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000023
Gregory P. Smithcd54e542010-01-03 00:29:15 +000024# Were we compiled --with-pydebug or with #define Py_DEBUG?
25COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
26
Christian Heimes3626a502013-10-19 14:12:02 +020027c_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
28py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
Gregory P. Smithcd54e542010-01-03 00:29:15 +000029
Christian Heimes121b9482016-09-06 22:03:25 +020030try:
31 import _blake2
32except ImportError:
33 _blake2 = None
34
35requires_blake2 = unittest.skipUnless(_blake2, 'requires _blake2')
36
37
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000038def hexstr(s):
Guido van Rossum5ed033b2007-07-09 14:29:40 +000039 assert isinstance(s, bytes), repr(s)
Guido van Rossum558ca842007-07-10 20:31:05 +000040 h = "0123456789abcdef"
41 r = ''
Guido van Rossum5ed033b2007-07-09 14:29:40 +000042 for i in s:
Guido van Rossum558ca842007-07-10 20:31:05 +000043 r += h[(i >> 4) & 0xF] + h[i & 0xF]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000044 return r
45
46
Christian Heimes121b9482016-09-06 22:03:25 +020047URL = "https://raw.githubusercontent.com/tiran/python_vectors/master/{}.txt"
48
49def read_vectors(hash_name):
50 with support.open_urlresource(URL.format(hash_name)) as f:
51 for line in f:
52 line = line.strip()
53 if line.startswith('#') or not line:
54 continue
55 parts = line.split(',')
56 parts[0] = bytes.fromhex(parts[0])
57 yield parts
58
59
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000060class HashLibTestCase(unittest.TestCase):
61 supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
62 'sha224', 'SHA224', 'sha256', 'SHA256',
Christian Heimes121b9482016-09-06 22:03:25 +020063 'sha384', 'SHA384', 'sha512', 'SHA512',
64 'blake2b', 'blake2s')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000065
Antoine Pitrou019ff192012-05-16 16:41:26 +020066 # Issue #14693: fallback modules are always compiled under POSIX
67 _warn_on_extension_import = os.name == 'posix' or COMPILED_WITH_PYDEBUG
Gregory P. Smithcd54e542010-01-03 00:29:15 +000068
69 def _conditional_import_module(self, module_name):
70 """Import a module and return a reference to it or None on failure."""
71 try:
72 exec('import '+module_name)
73 except ImportError as error:
74 if self._warn_on_extension_import:
75 warnings.warn('Did a C extension fail to compile? %s' % error)
76 return locals().get(module_name)
77
78 def __init__(self, *args, **kwargs):
79 algorithms = set()
80 for algorithm in self.supported_hash_names:
81 algorithms.add(algorithm.lower())
Christian Heimes121b9482016-09-06 22:03:25 +020082
83 _blake2 = self._conditional_import_module('_blake2')
84 if _blake2:
85 algorithms.update({'blake2b', 'blake2s'})
86
Gregory P. Smithcd54e542010-01-03 00:29:15 +000087 self.constructors_to_test = {}
88 for algorithm in algorithms:
89 self.constructors_to_test[algorithm] = set()
90
91 # For each algorithm, test the direct constructor and the use
92 # of hashlib.new given the algorithm name.
93 for algorithm, constructors in self.constructors_to_test.items():
94 constructors.add(getattr(hashlib, algorithm))
Christian Heimes121b9482016-09-06 22:03:25 +020095 def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, **kwargs):
Gregory P. Smithcd54e542010-01-03 00:29:15 +000096 if data is None:
Christian Heimes121b9482016-09-06 22:03:25 +020097 return hashlib.new(_alg, **kwargs)
98 return hashlib.new(_alg, data, **kwargs)
Gregory P. Smithcd54e542010-01-03 00:29:15 +000099 constructors.add(_test_algorithm_via_hashlib_new)
100
101 _hashlib = self._conditional_import_module('_hashlib')
102 if _hashlib:
103 # These two algorithms should always be present when this module
104 # is compiled. If not, something was compiled wrong.
Gregory P. Smith914061a2013-08-05 13:14:37 -0700105 self.assertTrue(hasattr(_hashlib, 'openssl_md5'))
106 self.assertTrue(hasattr(_hashlib, 'openssl_sha1'))
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000107 for algorithm, constructors in self.constructors_to_test.items():
108 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
109 if constructor:
110 constructors.add(constructor)
111
Christian Heimese5351072013-10-22 14:59:12 +0200112 def add_builtin_constructor(name):
113 constructor = getattr(hashlib, "__get_builtin_constructor")(name)
114 self.constructors_to_test[name].add(constructor)
115
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000116 _md5 = self._conditional_import_module('_md5')
117 if _md5:
Christian Heimese5351072013-10-22 14:59:12 +0200118 add_builtin_constructor('md5')
Gregory P. Smithb04ded42010-01-03 00:38:10 +0000119 _sha1 = self._conditional_import_module('_sha1')
120 if _sha1:
Christian Heimese5351072013-10-22 14:59:12 +0200121 add_builtin_constructor('sha1')
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000122 _sha256 = self._conditional_import_module('_sha256')
123 if _sha256:
Christian Heimese5351072013-10-22 14:59:12 +0200124 add_builtin_constructor('sha224')
125 add_builtin_constructor('sha256')
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000126 _sha512 = self._conditional_import_module('_sha512')
127 if _sha512:
Christian Heimese5351072013-10-22 14:59:12 +0200128 add_builtin_constructor('sha384')
129 add_builtin_constructor('sha512')
Christian Heimes121b9482016-09-06 22:03:25 +0200130 if _blake2:
131 add_builtin_constructor('blake2s')
132 add_builtin_constructor('blake2b')
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000133
134 super(HashLibTestCase, self).__init__(*args, **kwargs)
135
Christian Heimes65aa5732013-07-30 15:33:30 +0200136 @property
137 def hash_constructors(self):
138 constructors = self.constructors_to_test.values()
139 return itertools.chain.from_iterable(constructors)
140
Benjamin Petersona28e7022010-01-09 18:53:06 +0000141 def test_hash_array(self):
142 a = array.array("b", range(10))
Christian Heimes65aa5732013-07-30 15:33:30 +0200143 for cons in self.hash_constructors:
Benjamin Petersona28e7022010-01-09 18:53:06 +0000144 c = cons(a)
145 c.hexdigest()
146
Gregory P. Smith13b55292010-09-06 08:30:23 +0000147 def test_algorithms_guaranteed(self):
148 self.assertEqual(hashlib.algorithms_guaranteed,
Raymond Hettingerbf1d2bc2011-01-24 04:52:27 +0000149 set(_algo for _algo in self.supported_hash_names
Gregory P. Smith86508cc2010-03-01 02:05:26 +0000150 if _algo.islower()))
151
Gregory P. Smith13b55292010-09-06 08:30:23 +0000152 def test_algorithms_available(self):
153 self.assertTrue(set(hashlib.algorithms_guaranteed).
154 issubset(hashlib.algorithms_available))
155
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000156 def test_unknown_hash(self):
Amaury Forgeot d'Arc3a3dc172012-06-29 01:53:13 +0200157 self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
158 self.assertRaises(TypeError, hashlib.new, 1)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000159
Gregory P. Smith12c9d022011-05-14 15:15:49 -0700160 def test_get_builtin_constructor(self):
Christian Heimese5351072013-10-22 14:59:12 +0200161 get_builtin_constructor = getattr(hashlib,
162 '__get_builtin_constructor')
163 builtin_constructor_cache = getattr(hashlib,
164 '__builtin_constructor_cache')
Gregory P. Smith12c9d022011-05-14 15:15:49 -0700165 self.assertRaises(ValueError, get_builtin_constructor, 'test')
166 try:
167 import _md5
168 except ImportError:
169 pass
170 # This forces an ImportError for "import _md5" statements
171 sys.modules['_md5'] = None
Christian Heimese5351072013-10-22 14:59:12 +0200172 # clear the cache
173 builtin_constructor_cache.clear()
Gregory P. Smith12c9d022011-05-14 15:15:49 -0700174 try:
175 self.assertRaises(ValueError, get_builtin_constructor, 'md5')
176 finally:
177 if '_md5' in locals():
178 sys.modules['_md5'] = _md5
179 else:
180 del sys.modules['_md5']
Gregory P. Smith76c28f72012-07-21 21:19:53 -0700181 self.assertRaises(TypeError, get_builtin_constructor, 3)
Christian Heimese5351072013-10-22 14:59:12 +0200182 constructor = get_builtin_constructor('md5')
183 self.assertIs(constructor, _md5.md5)
184 self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5'])
Gregory P. Smith12c9d022011-05-14 15:15:49 -0700185
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000186 def test_hexdigest(self):
Christian Heimes65aa5732013-07-30 15:33:30 +0200187 for cons in self.hash_constructors:
188 h = cons()
Gregory P. Smith914061a2013-08-05 13:14:37 -0700189 self.assertIsInstance(h.digest(), bytes)
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000190 self.assertEqual(hexstr(h.digest()), h.hexdigest())
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000191
Jason R. Coombsb2aa6f42013-08-03 11:39:39 +0200192 def test_name_attribute(self):
193 for cons in self.hash_constructors:
194 h = cons()
Gregory P. Smith914061a2013-08-05 13:14:37 -0700195 self.assertIsInstance(h.name, str)
196 self.assertIn(h.name, self.supported_hash_names)
197 self.assertEqual(h.name, hashlib.new(h.name).name)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000198
199 def test_large_update(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000200 aas = b'a' * 128
201 bees = b'b' * 127
202 cees = b'c' * 126
Christian Heimes65aa5732013-07-30 15:33:30 +0200203 dees = b'd' * 2048 # HASHLIB_GIL_MINSIZE
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000204
Christian Heimes65aa5732013-07-30 15:33:30 +0200205 for cons in self.hash_constructors:
206 m1 = cons()
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000207 m1.update(aas)
208 m1.update(bees)
209 m1.update(cees)
Christian Heimes65aa5732013-07-30 15:33:30 +0200210 m1.update(dees)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000211
Christian Heimes65aa5732013-07-30 15:33:30 +0200212 m2 = cons()
213 m2.update(aas + bees + cees + dees)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000214 self.assertEqual(m1.digest(), m2.digest())
215
Christian Heimes65aa5732013-07-30 15:33:30 +0200216 m3 = cons(aas + bees + cees + dees)
217 self.assertEqual(m1.digest(), m3.digest())
218
219 # verify copy() doesn't touch original
220 m4 = cons(aas + bees + cees)
221 m4_digest = m4.digest()
222 m4_copy = m4.copy()
223 m4_copy.update(dees)
224 self.assertEqual(m1.digest(), m4_copy.digest())
225 self.assertEqual(m4.digest(), m4_digest)
226
Christian Heimes121b9482016-09-06 22:03:25 +0200227 def check(self, name, data, hexdigest, **kwargs):
Christian Heimes65aa5732013-07-30 15:33:30 +0200228 hexdigest = hexdigest.lower()
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000229 constructors = self.constructors_to_test[name]
230 # 2 is for hashlib.name(...) and hashlib.new(name, ...)
231 self.assertGreaterEqual(len(constructors), 2)
232 for hash_object_constructor in constructors:
Christian Heimes121b9482016-09-06 22:03:25 +0200233 m = hash_object_constructor(data, **kwargs)
Christian Heimes65aa5732013-07-30 15:33:30 +0200234 computed = m.hexdigest()
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000235 self.assertEqual(
Christian Heimes65aa5732013-07-30 15:33:30 +0200236 computed, hexdigest,
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000237 "Hash algorithm %s constructed using %s returned hexdigest"
238 " %r for %d byte input data that should have hashed to %r."
239 % (name, hash_object_constructor,
Christian Heimes65aa5732013-07-30 15:33:30 +0200240 computed, len(data), hexdigest))
241 computed = m.digest()
242 digest = bytes.fromhex(hexdigest)
243 self.assertEqual(computed, digest)
244 self.assertEqual(len(digest), m.digest_size)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000245
Gregory P. Smith365a1862009-02-12 07:35:29 +0000246 def check_no_unicode(self, algorithm_name):
247 # Unicode objects are not allowed as input.
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000248 constructors = self.constructors_to_test[algorithm_name]
249 for hash_object_constructor in constructors:
250 self.assertRaises(TypeError, hash_object_constructor, 'spam')
Gregory P. Smith365a1862009-02-12 07:35:29 +0000251
252 def test_no_unicode(self):
253 self.check_no_unicode('md5')
254 self.check_no_unicode('sha1')
255 self.check_no_unicode('sha224')
256 self.check_no_unicode('sha256')
257 self.check_no_unicode('sha384')
258 self.check_no_unicode('sha512')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000259
Christian Heimes121b9482016-09-06 22:03:25 +0200260 @requires_blake2
261 def test_no_unicode_blake2(self):
262 self.check_no_unicode('blake2b')
263 self.check_no_unicode('blake2s')
264
Christian Heimes65aa5732013-07-30 15:33:30 +0200265 def check_blocksize_name(self, name, block_size=0, digest_size=0):
266 constructors = self.constructors_to_test[name]
267 for hash_object_constructor in constructors:
268 m = hash_object_constructor()
269 self.assertEqual(m.block_size, block_size)
270 self.assertEqual(m.digest_size, digest_size)
271 self.assertEqual(len(m.digest()), digest_size)
Christian Heimes37d5ceb2013-08-15 18:31:48 +0200272 self.assertEqual(m.name, name)
Christian Heimesd49a3712013-07-30 15:35:54 +0200273 # split for sha3_512 / _sha3.sha3 object
Christian Heimes37d5ceb2013-08-15 18:31:48 +0200274 self.assertIn(name.split("_")[0], repr(m))
Christian Heimes65aa5732013-07-30 15:33:30 +0200275
276 def test_blocksize_name(self):
277 self.check_blocksize_name('md5', 64, 16)
278 self.check_blocksize_name('sha1', 64, 20)
279 self.check_blocksize_name('sha224', 64, 28)
280 self.check_blocksize_name('sha256', 64, 32)
281 self.check_blocksize_name('sha384', 128, 48)
282 self.check_blocksize_name('sha512', 128, 64)
283
Christian Heimes121b9482016-09-06 22:03:25 +0200284 @requires_blake2
285 def test_blocksize_name_blake2(self):
286 self.check_blocksize_name('blake2b', 128, 64)
287 self.check_blocksize_name('blake2s', 64, 32)
288
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000289 def test_case_md5_0(self):
Guido van Rossum558ca842007-07-10 20:31:05 +0000290 self.check('md5', b'', 'd41d8cd98f00b204e9800998ecf8427e')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000291
292 def test_case_md5_1(self):
Guido van Rossum558ca842007-07-10 20:31:05 +0000293 self.check('md5', b'abc', '900150983cd24fb0d6963f7d28e17f72')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000294
295 def test_case_md5_2(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000296 self.check('md5',
297 b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
Guido van Rossum558ca842007-07-10 20:31:05 +0000298 'd174ab98d277d9f5a5611c2c9f419d9f')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000299
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200300 @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
301 @bigmemtest(size=_4G + 5, memuse=1, dry_run=False)
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000302 def test_case_md5_huge(self, size):
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200303 self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000304
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200305 @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems')
306 @bigmemtest(size=_4G - 1, memuse=1, dry_run=False)
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000307 def test_case_md5_uintmax(self, size):
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200308 self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000309
310 # use the three examples from Federal Information Processing Standards
311 # Publication 180-1, Secure Hash Standard, 1995 April 17
312 # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
313
314 def test_case_sha1_0(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000315 self.check('sha1', b"",
Guido van Rossum558ca842007-07-10 20:31:05 +0000316 "da39a3ee5e6b4b0d3255bfef95601890afd80709")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000317
318 def test_case_sha1_1(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000319 self.check('sha1', b"abc",
Guido van Rossum558ca842007-07-10 20:31:05 +0000320 "a9993e364706816aba3e25717850c26c9cd0d89d")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000321
322 def test_case_sha1_2(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000323 self.check('sha1',
324 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Guido van Rossum558ca842007-07-10 20:31:05 +0000325 "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000326
327 def test_case_sha1_3(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000328 self.check('sha1', b"a" * 1000000,
Guido van Rossum558ca842007-07-10 20:31:05 +0000329 "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000330
331
332 # use the examples from Federal Information Processing Standards
333 # Publication 180-2, Secure Hash Standard, 2002 August 1
334 # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
335
336 def test_case_sha224_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000337 self.check('sha224', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000338 "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
339
340 def test_case_sha224_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000341 self.check('sha224', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000342 "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
343
344 def test_case_sha224_2(self):
345 self.check('sha224',
Guido van Rossume22905a2007-08-27 23:09:25 +0000346 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000347 "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
348
349 def test_case_sha224_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000350 self.check('sha224', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000351 "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
352
353
354 def test_case_sha256_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000355 self.check('sha256', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000356 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
357
358 def test_case_sha256_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000359 self.check('sha256', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000360 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
361
362 def test_case_sha256_2(self):
363 self.check('sha256',
Guido van Rossume22905a2007-08-27 23:09:25 +0000364 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000365 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
366
367 def test_case_sha256_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000368 self.check('sha256', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000369 "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
370
371
372 def test_case_sha384_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000373 self.check('sha384', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000374 "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
375 "274edebfe76f65fbd51ad2f14898b95b")
376
377 def test_case_sha384_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000378 self.check('sha384', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000379 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
380 "8086072ba1e7cc2358baeca134c825a7")
381
382 def test_case_sha384_2(self):
383 self.check('sha384',
Guido van Rossume22905a2007-08-27 23:09:25 +0000384 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
385 b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000386 "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
387 "fcc7c71a557e2db966c3e9fa91746039")
388
389 def test_case_sha384_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000390 self.check('sha384', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000391 "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
392 "07b8b3dc38ecc4ebae97ddd87f3d8985")
393
394
395 def test_case_sha512_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000396 self.check('sha512', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000397 "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
398 "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
399
400 def test_case_sha512_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000401 self.check('sha512', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000402 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
403 "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
404
405 def test_case_sha512_2(self):
406 self.check('sha512',
Guido van Rossume22905a2007-08-27 23:09:25 +0000407 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
408 b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000409 "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
410 "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
411
412 def test_case_sha512_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000413 self.check('sha512', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000414 "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
415 "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
416
Christian Heimes121b9482016-09-06 22:03:25 +0200417 def check_blake2(self, constructor, salt_size, person_size, key_size,
418 digest_size, max_offset):
419 self.assertEqual(constructor.SALT_SIZE, salt_size)
420 for i in range(salt_size + 1):
421 constructor(salt=b'a' * i)
422 salt = b'a' * (salt_size + 1)
423 self.assertRaises(ValueError, constructor, salt=salt)
424
425 self.assertEqual(constructor.PERSON_SIZE, person_size)
426 for i in range(person_size+1):
427 constructor(person=b'a' * i)
428 person = b'a' * (person_size + 1)
429 self.assertRaises(ValueError, constructor, person=person)
430
431 self.assertEqual(constructor.MAX_DIGEST_SIZE, digest_size)
432 for i in range(1, digest_size + 1):
433 constructor(digest_size=i)
434 self.assertRaises(ValueError, constructor, digest_size=-1)
435 self.assertRaises(ValueError, constructor, digest_size=0)
436 self.assertRaises(ValueError, constructor, digest_size=digest_size+1)
437
438 self.assertEqual(constructor.MAX_KEY_SIZE, key_size)
439 for i in range(key_size+1):
440 constructor(key=b'a' * i)
441 key = b'a' * (key_size + 1)
442 self.assertRaises(ValueError, constructor, key=key)
443 self.assertEqual(constructor().hexdigest(),
444 constructor(key=b'').hexdigest())
445
446 for i in range(0, 256):
447 constructor(fanout=i)
448 self.assertRaises(ValueError, constructor, fanout=-1)
449 self.assertRaises(ValueError, constructor, fanout=256)
450
451 for i in range(1, 256):
452 constructor(depth=i)
453 self.assertRaises(ValueError, constructor, depth=-1)
454 self.assertRaises(ValueError, constructor, depth=0)
455 self.assertRaises(ValueError, constructor, depth=256)
456
457 for i in range(0, 256):
458 constructor(node_depth=i)
459 self.assertRaises(ValueError, constructor, node_depth=-1)
460 self.assertRaises(ValueError, constructor, node_depth=256)
461
462 for i in range(0, digest_size + 1):
463 constructor(inner_size=i)
464 self.assertRaises(ValueError, constructor, inner_size=-1)
465 self.assertRaises(ValueError, constructor, inner_size=digest_size+1)
466
467 constructor(leaf_size=0)
468 constructor(leaf_size=(1<<32)-1)
469 self.assertRaises(OverflowError, constructor, leaf_size=-1)
470 self.assertRaises(OverflowError, constructor, leaf_size=1<<32)
471
472 constructor(node_offset=0)
473 constructor(node_offset=max_offset)
474 self.assertRaises(OverflowError, constructor, node_offset=-1)
475 self.assertRaises(OverflowError, constructor, node_offset=max_offset+1)
476
477 constructor(
478 string=b'',
479 key=b'',
480 salt=b'',
481 person=b'',
482 digest_size=17,
483 fanout=1,
484 depth=1,
485 leaf_size=256,
486 node_offset=512,
487 node_depth=1,
488 inner_size=7,
489 last_node=True
490 )
491
492 def blake2_rfc7693(self, constructor, md_len, in_len):
493 def selftest_seq(length, seed):
494 mask = (1<<32)-1
495 a = (0xDEAD4BAD * seed) & mask
496 b = 1
497 out = bytearray(length)
498 for i in range(length):
499 t = (a + b) & mask
500 a, b = b, t
501 out[i] = (t >> 24) & 0xFF
502 return out
503 outer = constructor(digest_size=32)
504 for outlen in md_len:
505 for inlen in in_len:
506 indata = selftest_seq(inlen, inlen)
507 key = selftest_seq(outlen, outlen)
508 unkeyed = constructor(indata, digest_size=outlen)
509 outer.update(unkeyed.digest())
510 keyed = constructor(indata, key=key, digest_size=outlen)
511 outer.update(keyed.digest())
512 return outer.hexdigest()
513
514 @requires_blake2
515 def test_blake2b(self):
516 self.check_blake2(hashlib.blake2b, 16, 16, 64, 64, (1<<64)-1)
517 b2b_md_len = [20, 32, 48, 64]
518 b2b_in_len = [0, 3, 128, 129, 255, 1024]
519 self.assertEqual(
520 self.blake2_rfc7693(hashlib.blake2b, b2b_md_len, b2b_in_len),
521 "c23a7800d98123bd10f506c61e29da5603d763b8bbad2e737f5e765a7bccd475")
522
523 @requires_blake2
524 def test_case_blake2b_0(self):
525 self.check('blake2b', b"",
526 "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419"+
527 "d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce")
528
529 @requires_blake2
530 def test_case_blake2b_1(self):
531 self.check('blake2b', b"abc",
532 "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1"+
533 "7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923")
534
535 @requires_blake2
536 def test_blake2b_vectors(self):
537 for msg, key, md in read_vectors('blake2b'):
538 key = bytes.fromhex(key)
539 self.check('blake2b', msg, md, key=key)
540
541 @requires_blake2
542 def test_blake2s(self):
543 self.check_blake2(hashlib.blake2s, 8, 8, 32, 32, (1<<48)-1)
544 b2s_md_len = [16, 20, 28, 32]
545 b2s_in_len = [0, 3, 64, 65, 255, 1024]
546 self.assertEqual(
547 self.blake2_rfc7693(hashlib.blake2s, b2s_md_len, b2s_in_len),
548 "6a411f08ce25adcdfb02aba641451cec53c598b24f4fc787fbdc88797f4c1dfe")
549
550 @requires_blake2
551 def test_case_blake2s_0(self):
552 self.check('blake2s', b"",
553 "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9")
554
555 @requires_blake2
556 def test_case_blake2s_1(self):
557 self.check('blake2s', b"abc",
558 "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982")
559
560 @requires_blake2
561 def test_blake2s_vectors(self):
562 for msg, key, md in read_vectors('blake2s'):
563 key = bytes.fromhex(key)
564 self.check('blake2s', msg, md, key=key)
565
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000566 def test_gil(self):
567 # Check things work fine with an input larger than the size required
568 # for multithreaded operation (which is hardwired to 2048).
569 gil_minsize = 2048
570
Christian Heimes65aa5732013-07-30 15:33:30 +0200571 for cons in self.hash_constructors:
572 m = cons()
Christian Heimes4a0270d2012-10-06 02:23:36 +0200573 m.update(b'1')
574 m.update(b'#' * gil_minsize)
575 m.update(b'1')
576
Christian Heimes65aa5732013-07-30 15:33:30 +0200577 m = cons(b'x' * gil_minsize)
Christian Heimes4a0270d2012-10-06 02:23:36 +0200578 m.update(b'1')
579
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000580 m = hashlib.md5()
581 m.update(b'1')
582 m.update(b'#' * gil_minsize)
583 m.update(b'1')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000584 self.assertEqual(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21')
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000585
586 m = hashlib.md5(b'x' * gil_minsize)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000587 self.assertEqual(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000588
Victor Stinner45df8202010-04-28 22:31:17 +0000589 @unittest.skipUnless(threading, 'Threading required for this test.')
590 @support.reap_threads
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000591 def test_threaded_hashing(self):
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000592 # Updating the same hash object from several threads at once
593 # using data chunk sizes containing the same byte sequences.
594 #
595 # If the internal locks are working to prevent multiple
596 # updates on the same object from running at once, the resulting
597 # hash will be the same as doing it single threaded upfront.
598 hasher = hashlib.sha1()
599 num_threads = 5
600 smallest_data = b'swineflu'
601 data = smallest_data*200000
602 expected_hash = hashlib.sha1(data*num_threads).hexdigest()
603
604 def hash_in_chunks(chunk_size, event):
605 index = 0
606 while index < len(data):
607 hasher.update(data[index:index+chunk_size])
608 index += chunk_size
609 event.set()
610
611 events = []
612 for threadnum in range(num_threads):
613 chunk_size = len(data) // (10**threadnum)
Gregory P. Smith914061a2013-08-05 13:14:37 -0700614 self.assertGreater(chunk_size, 0)
615 self.assertEqual(chunk_size % len(smallest_data), 0)
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000616 event = threading.Event()
617 events.append(event)
618 threading.Thread(target=hash_in_chunks,
619 args=(chunk_size, event)).start()
620
621 for event in events:
622 event.wait()
623
624 self.assertEqual(expected_hash, hasher.hexdigest())
625
Christian Heimes3626a502013-10-19 14:12:02 +0200626
Christian Heimes0fbd94c2013-10-19 19:40:49 +0200627class KDFTests(unittest.TestCase):
Christian Heimes3626a502013-10-19 14:12:02 +0200628
Christian Heimese92ef132013-10-13 00:52:43 +0200629 pbkdf2_test_vectors = [
630 (b'password', b'salt', 1, None),
631 (b'password', b'salt', 2, None),
632 (b'password', b'salt', 4096, None),
633 # too slow, it takes over a minute on a fast CPU.
634 #(b'password', b'salt', 16777216, None),
635 (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt',
636 4096, -1),
637 (b'pass\0word', b'sa\0lt', 4096, 16),
638 ]
639
Christian Heimes39093e92016-09-06 20:22:28 +0200640 scrypt_test_vectors = [
641 (b'', b'', 16, 1, 1, unhexlify('77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906')),
642 (b'password', b'NaCl', 1024, 8, 16, unhexlify('fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640')),
643 (b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, unhexlify('7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887')),
644 ]
645
Christian Heimese92ef132013-10-13 00:52:43 +0200646 pbkdf2_results = {
647 "sha1": [
Martin Panter46f50722016-05-26 05:35:26 +0000648 # official test vectors from RFC 6070
Christian Heimese92ef132013-10-13 00:52:43 +0200649 (bytes.fromhex('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None),
650 (bytes.fromhex('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None),
651 (bytes.fromhex('4b007901b765489abead49d926f721d065a429c1'), None),
652 #(bytes.fromhex('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None),
653 (bytes.fromhex('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c'
654 'f2f07038'), 25),
655 (bytes.fromhex('56fa6aa75548099dcc37d7f03425e0c3'), None),],
656 "sha256": [
657 (bytes.fromhex('120fb6cffcf8b32c43e7225256c4f837'
658 'a86548c92ccc35480805987cb70be17b'), None),
659 (bytes.fromhex('ae4d0c95af6b46d32d0adff928f06dd0'
660 '2a303f8ef3c251dfd6e2d85a95474c43'), None),
661 (bytes.fromhex('c5e478d59288c841aa530db6845c4c8d'
662 '962893a001ce4e11a4963873aa98134a'), None),
663 #(bytes.fromhex('cf81c66fe8cfc04d1f31ecb65dab4089'
664 # 'f7f179e89b3b0bcb17ad10e3ac6eba46'), None),
665 (bytes.fromhex('348c89dbcbd32b2f32d814b8116e84cf2b17'
666 '347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40),
667 (bytes.fromhex('89b69d0516f829893c696226650a8687'), None),],
668 "sha512": [
669 (bytes.fromhex('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5'
670 'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f'
671 '050235d7d68b1da55e63f73b60a57fce'), None),
672 (bytes.fromhex('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071'
673 '3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82'
674 'be67335c77a6068e04112754f27ccf4e'), None),
675 (bytes.fromhex('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8'
676 '7f6902e072f457b5143f30602641b3d55cd335988cb36b84'
677 '376060ecd532e039b742a239434af2d5'), None),
678 (bytes.fromhex('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8'
679 '68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30'
680 '225c583a186cd82bd4daea9724a3d3b8'), 64),
681 (bytes.fromhex('9d9e9c4cd21fe4be24d5b8244c759665'), None),],
682 }
683
Christian Heimes0fbd94c2013-10-19 19:40:49 +0200684 def _test_pbkdf2_hmac(self, pbkdf2):
Christian Heimese92ef132013-10-13 00:52:43 +0200685 for digest_name, results in self.pbkdf2_results.items():
686 for i, vector in enumerate(self.pbkdf2_test_vectors):
687 password, salt, rounds, dklen = vector
688 expected, overwrite_dklen = results[i]
689 if overwrite_dklen:
690 dklen = overwrite_dklen
691 out = pbkdf2(digest_name, password, salt, rounds, dklen)
692 self.assertEqual(out, expected,
693 (digest_name, password, salt, rounds, dklen))
694 out = pbkdf2(digest_name, memoryview(password),
695 memoryview(salt), rounds, dklen)
696 out = pbkdf2(digest_name, bytearray(password),
697 bytearray(salt), rounds, dklen)
698 self.assertEqual(out, expected)
699 if dklen is None:
700 out = pbkdf2(digest_name, password, salt, rounds)
701 self.assertEqual(out, expected,
702 (digest_name, password, salt, rounds))
703
704 self.assertRaises(TypeError, pbkdf2, b'sha1', b'pass', b'salt', 1)
705 self.assertRaises(TypeError, pbkdf2, 'sha1', 'pass', 'salt', 1)
706 self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 0)
707 self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', -1)
708 self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, 0)
709 self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, -1)
710 with self.assertRaisesRegex(ValueError, 'unsupported hash type'):
711 pbkdf2('unknown', b'pass', b'salt', 1)
Martin Panterbc85e352016-02-22 09:21:49 +0000712 out = pbkdf2(hash_name='sha1', password=b'password', salt=b'salt',
713 iterations=1, dklen=None)
714 self.assertEqual(out, self.pbkdf2_results['sha1'][0][0])
Christian Heimese92ef132013-10-13 00:52:43 +0200715
Christian Heimes0fbd94c2013-10-19 19:40:49 +0200716 def test_pbkdf2_hmac_py(self):
717 self._test_pbkdf2_hmac(py_hashlib.pbkdf2_hmac)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000718
Christian Heimes0fbd94c2013-10-19 19:40:49 +0200719 @unittest.skipUnless(hasattr(c_hashlib, 'pbkdf2_hmac'),
720 ' test requires OpenSSL > 1.0')
721 def test_pbkdf2_hmac_c(self):
722 self._test_pbkdf2_hmac(c_hashlib.pbkdf2_hmac)
Christian Heimes3626a502013-10-19 14:12:02 +0200723
724
Christian Heimes39093e92016-09-06 20:22:28 +0200725 @unittest.skipUnless(hasattr(c_hashlib, 'scrypt'),
726 ' test requires OpenSSL > 1.1')
727 def test_scrypt(self):
728 for password, salt, n, r, p, expected in self.scrypt_test_vectors:
729 result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p)
730 self.assertEqual(result, expected)
731
732 # this values should work
733 hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1)
734 # password and salt must be bytes-like
735 with self.assertRaises(TypeError):
736 hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1)
737 with self.assertRaises(TypeError):
738 hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1)
739 # require keyword args
740 with self.assertRaises(TypeError):
741 hashlib.scrypt(b'password')
742 with self.assertRaises(TypeError):
743 hashlib.scrypt(b'password', b'salt')
744 with self.assertRaises(TypeError):
745 hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt')
746 for n in [-1, 0, 1, None]:
747 with self.assertRaises((ValueError, OverflowError, TypeError)):
748 hashlib.scrypt(b'password', salt=b'salt', n=n, r=8, p=1)
749 for r in [-1, 0, None]:
750 with self.assertRaises((ValueError, OverflowError, TypeError)):
751 hashlib.scrypt(b'password', salt=b'salt', n=2, r=r, p=1)
752 for p in [-1, 0, None]:
753 with self.assertRaises((ValueError, OverflowError, TypeError)):
754 hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=p)
755 for maxmem in [-1, None]:
756 with self.assertRaises((ValueError, OverflowError, TypeError)):
757 hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
758 maxmem=maxmem)
759 for dklen in [-1, None]:
760 with self.assertRaises((ValueError, OverflowError, TypeError)):
761 hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
762 dklen=dklen)
763
764
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000765if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400766 unittest.main()