blob: 91080955ddd24c2a2e6d33534ad952da87fb9b25 [file] [log] [blame]
Gregory P. Smith13b55292010-09-06 08:30:23 +00001# Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00002# Licensed to PSF under a Contributor Agreement.
3#
4
5__doc__ = """hashlib module - A common interface to many hash functions.
6
Guido van Rossume22905a2007-08-27 23:09:25 +00007new(name, data=b'') - returns a new hash object implementing the
8 given hash function; initializing the hash
9 using the given binary data.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000010
Gregory P. Smith2f21eb32007-09-09 06:44:34 +000011Named constructor functions are also available, these are faster
12than using new(name):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000013
14md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
15
Gregory P. Smith13b55292010-09-06 08:30:23 +000016More algorithms may be available on your platform but the above are guaranteed
17to exist. See the algorithms_guaranteed and algorithms_available attributes
18to find out what algorithm names can be passed to new().
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000019
Christian Heimesd5e2b6f2008-03-19 21:50:51 +000020NOTE: If you want the adler32 or crc32 hash functions they are available in
21the zlib module.
22
Thomas Wouters89f507f2006-12-13 04:49:30 +000023Choose your hash function wisely. Some have known collision weaknesses.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000024sha384 and sha512 will be slow on 32 bit platforms.
Thomas Wouters89f507f2006-12-13 04:49:30 +000025
26Hash objects have these methods:
Gregory P. Smith2f21eb32007-09-09 06:44:34 +000027 - update(arg): Update the hash object with the bytes in arg. Repeated calls
Thomas Wouters89f507f2006-12-13 04:49:30 +000028 are equivalent to a single call with the concatenation of all
29 the arguments.
Gregory P. Smith2f21eb32007-09-09 06:44:34 +000030 - digest(): Return the digest of the bytes passed to the update() method
31 so far.
32 - hexdigest(): Like digest() except the digest is returned as a unicode
33 object of double length, containing only hexadecimal digits.
Thomas Wouters89f507f2006-12-13 04:49:30 +000034 - copy(): Return a copy (clone) of the hash object. This can be used to
35 efficiently compute the digests of strings that share a common
36 initial substring.
37
38For example, to obtain the digest of the string 'Nobody inspects the
39spammish repetition':
40
41 >>> import hashlib
42 >>> m = hashlib.md5()
Guido van Rossume22905a2007-08-27 23:09:25 +000043 >>> m.update(b"Nobody inspects")
44 >>> m.update(b" the spammish repetition")
Thomas Wouters89f507f2006-12-13 04:49:30 +000045 >>> m.digest()
Gregory P. Smith63594502008-08-31 16:35:01 +000046 b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
Thomas Wouters89f507f2006-12-13 04:49:30 +000047
48More condensed:
49
Guido van Rossume22905a2007-08-27 23:09:25 +000050 >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
Thomas Wouters89f507f2006-12-13 04:49:30 +000051 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
52
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000053"""
54
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +000055# This tuple and __get_builtin_constructor() must be modified if a new
56# always available algorithm is added.
57__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
58
Raymond Hettingerbf1d2bc2011-01-24 04:52:27 +000059algorithms_guaranteed = set(__always_supported)
60algorithms_available = set(__always_supported)
Gregory P. Smith86508cc2010-03-01 02:05:26 +000061
Gregory P. Smith13b55292010-09-06 08:30:23 +000062__all__ = __always_supported + ('new', 'algorithms_guaranteed',
63 'algorithms_available')
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +000064
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000065
66def __get_builtin_constructor(name):
Gregory P. Smith79aa5bf2011-05-14 15:15:49 -070067 try:
68 if name in ('SHA1', 'sha1'):
69 import _sha1
70 return _sha1.sha1
71 elif name in ('MD5', 'md5'):
72 import _md5
73 return _md5.md5
74 elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
75 import _sha256
76 bs = name[3:]
77 if bs == '256':
78 return _sha256.sha256
79 elif bs == '224':
80 return _sha256.sha224
81 elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
82 import _sha512
83 bs = name[3:]
84 if bs == '512':
85 return _sha512.sha512
86 elif bs == '384':
87 return _sha512.sha384
88 except ImportError:
Gregory P. Smith369f35a2011-05-14 15:35:56 -070089 pass # no extension module, this hash is unsupported.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000090
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +000091 raise ValueError('unsupported hash type %s' % name)
92
93
94def __get_openssl_constructor(name):
95 try:
96 f = getattr(_hashlib, 'openssl_' + name)
97 # Allow the C module to raise ValueError. The function will be
98 # defined but the hash not actually available thanks to OpenSSL.
99 f()
100 # Use the C function directly (very fast)
101 return f
102 except (AttributeError, ValueError):
103 return __get_builtin_constructor(name)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000104
105
Guido van Rossume22905a2007-08-27 23:09:25 +0000106def __py_new(name, data=b''):
Gregory P. Smith2f21eb32007-09-09 06:44:34 +0000107 """new(name, data=b'') - Return a new hashing object using the named algorithm;
Guido van Rossume22905a2007-08-27 23:09:25 +0000108 optionally initialized with data (which must be bytes).
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000109 """
Guido van Rossume22905a2007-08-27 23:09:25 +0000110 return __get_builtin_constructor(name)(data)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000111
112
Guido van Rossume22905a2007-08-27 23:09:25 +0000113def __hash_new(name, data=b''):
114 """new(name, data=b'') - Return a new hashing object using the named algorithm;
115 optionally initialized with data (which must be bytes).
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000116 """
117 try:
Guido van Rossume22905a2007-08-27 23:09:25 +0000118 return _hashlib.new(name, data)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000119 except ValueError:
120 # If the _hashlib module (OpenSSL) doesn't support the named
121 # hash, try using our builtin implementations.
122 # This allows for SHA224/256 and SHA384/512 support even though
123 # the OpenSSL library prior to 0.9.8 doesn't provide them.
Guido van Rossume22905a2007-08-27 23:09:25 +0000124 return __get_builtin_constructor(name)(data)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000125
126
127try:
128 import _hashlib
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000129 new = __hash_new
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +0000130 __get_hash = __get_openssl_constructor
Gregory P. Smith13b55292010-09-06 08:30:23 +0000131 algorithms_available = algorithms_available.union(
132 _hashlib.openssl_md_meth_names)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000133except ImportError:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000134 new = __py_new
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +0000135 __get_hash = __get_builtin_constructor
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000136
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +0000137for __func_name in __always_supported:
138 # try them all, some may not work due to the OpenSSL
139 # version not supporting that algorithm.
140 try:
141 globals()[__func_name] = __get_hash(__func_name)
142 except ValueError:
143 import logging
144 logging.exception('code for hash %s was not found.', __func_name)
145
146# Cleanup locals()
147del __always_supported, __func_name, __get_hash
148del __py_new, __hash_new, __get_openssl_constructor