blob: aacb268bfd4a2a4bc3de04021573275432d58ecc [file] [log] [blame]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001# $Id$
2#
Gregory P. Smith9406f5c2007-08-26 02:58:36 +00003# Copyright (C) 2005-2007 Gregory P. Smith (greg@krypto.org)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00004# Licensed to PSF under a Contributor Agreement.
5#
6
7__doc__ = """hashlib module - A common interface to many hash functions.
8
Guido van Rossume22905a2007-08-27 23:09:25 +00009new(name, data=b'') - returns a new hash object implementing the
10 given hash function; initializing the hash
11 using the given binary data.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000012
Gregory P. Smith2f21eb32007-09-09 06:44:34 +000013Named constructor functions are also available, these are faster
14than using new(name):
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000015
16md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
17
18More algorithms may be available on your platform but the above are
19guaranteed to exist.
20
Christian Heimesd5e2b6f2008-03-19 21:50:51 +000021NOTE: If you want the adler32 or crc32 hash functions they are available in
22the zlib module.
23
Thomas Wouters89f507f2006-12-13 04:49:30 +000024Choose your hash function wisely. Some have known collision weaknesses.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000025sha384 and sha512 will be slow on 32 bit platforms.
Thomas Wouters89f507f2006-12-13 04:49:30 +000026
27Hash objects have these methods:
Gregory P. Smith2f21eb32007-09-09 06:44:34 +000028 - update(arg): Update the hash object with the bytes in arg. Repeated calls
Thomas Wouters89f507f2006-12-13 04:49:30 +000029 are equivalent to a single call with the concatenation of all
30 the arguments.
Gregory P. Smith2f21eb32007-09-09 06:44:34 +000031 - digest(): Return the digest of the bytes passed to the update() method
32 so far.
33 - hexdigest(): Like digest() except the digest is returned as a unicode
34 object of double length, containing only hexadecimal digits.
Thomas Wouters89f507f2006-12-13 04:49:30 +000035 - copy(): Return a copy (clone) of the hash object. This can be used to
36 efficiently compute the digests of strings that share a common
37 initial substring.
38
39For example, to obtain the digest of the string 'Nobody inspects the
40spammish repetition':
41
42 >>> import hashlib
43 >>> m = hashlib.md5()
Guido van Rossume22905a2007-08-27 23:09:25 +000044 >>> m.update(b"Nobody inspects")
45 >>> m.update(b" the spammish repetition")
Thomas Wouters89f507f2006-12-13 04:49:30 +000046 >>> m.digest()
Gregory P. Smith63594502008-08-31 16:35:01 +000047 b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
Thomas Wouters89f507f2006-12-13 04:49:30 +000048
49More condensed:
50
Guido van Rossume22905a2007-08-27 23:09:25 +000051 >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
Thomas Wouters89f507f2006-12-13 04:49:30 +000052 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
53
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000054"""
55
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +000056# This tuple and __get_builtin_constructor() must be modified if a new
57# always available algorithm is added.
58__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
59
Gregory P. Smith86508cc2010-03-01 02:05:26 +000060algorithms = __always_supported
61
62__all__ = __always_supported + ('new', 'algorithms')
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +000063
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000064
65def __get_builtin_constructor(name):
66 if name in ('SHA1', 'sha1'):
Gregory P. Smith2f21eb32007-09-09 06:44:34 +000067 import _sha1
68 return _sha1.sha1
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000069 elif name in ('MD5', 'md5'):
70 import _md5
Gregory P. Smith2f21eb32007-09-09 06:44:34 +000071 return _md5.md5
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000072 elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
73 import _sha256
74 bs = name[3:]
75 if bs == '256':
76 return _sha256.sha256
77 elif bs == '224':
78 return _sha256.sha224
79 elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
80 import _sha512
81 bs = name[3:]
82 if bs == '512':
83 return _sha512.sha512
84 elif bs == '384':
85 return _sha512.sha384
86
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +000087 raise ValueError('unsupported hash type %s' % name)
88
89
90def __get_openssl_constructor(name):
91 try:
92 f = getattr(_hashlib, 'openssl_' + name)
93 # Allow the C module to raise ValueError. The function will be
94 # defined but the hash not actually available thanks to OpenSSL.
95 f()
96 # Use the C function directly (very fast)
97 return f
98 except (AttributeError, ValueError):
99 return __get_builtin_constructor(name)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000100
101
Guido van Rossume22905a2007-08-27 23:09:25 +0000102def __py_new(name, data=b''):
Gregory P. Smith2f21eb32007-09-09 06:44:34 +0000103 """new(name, data=b'') - Return a new hashing object using the named algorithm;
Guido van Rossume22905a2007-08-27 23:09:25 +0000104 optionally initialized with data (which must be bytes).
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000105 """
Guido van Rossume22905a2007-08-27 23:09:25 +0000106 return __get_builtin_constructor(name)(data)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000107
108
Guido van Rossume22905a2007-08-27 23:09:25 +0000109def __hash_new(name, data=b''):
110 """new(name, data=b'') - Return a new hashing object using the named algorithm;
111 optionally initialized with data (which must be bytes).
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000112 """
113 try:
Guido van Rossume22905a2007-08-27 23:09:25 +0000114 return _hashlib.new(name, data)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000115 except ValueError:
116 # If the _hashlib module (OpenSSL) doesn't support the named
117 # hash, try using our builtin implementations.
118 # This allows for SHA224/256 and SHA384/512 support even though
119 # the OpenSSL library prior to 0.9.8 doesn't provide them.
Guido van Rossume22905a2007-08-27 23:09:25 +0000120 return __get_builtin_constructor(name)(data)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000121
122
123try:
124 import _hashlib
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000125 new = __hash_new
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +0000126 __get_hash = __get_openssl_constructor
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000127except ImportError:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000128 new = __py_new
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +0000129 __get_hash = __get_builtin_constructor
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000130
Gregory P. Smithd8fe8bf2009-08-16 22:08:56 +0000131for __func_name in __always_supported:
132 # try them all, some may not work due to the OpenSSL
133 # version not supporting that algorithm.
134 try:
135 globals()[__func_name] = __get_hash(__func_name)
136 except ValueError:
137 import logging
138 logging.exception('code for hash %s was not found.', __func_name)
139
140# Cleanup locals()
141del __always_supported, __func_name, __get_hash
142del __py_new, __hash_new, __get_openssl_constructor