blob: 5ecca2bf63bc02d07e4ad9727996a93ca4862be7 [file] [log] [blame]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001# $Id$
2#
Gregory P. Smithf8057852007-09-09 20:25:00 +00003# Copyright (C) 2005 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
9new(name, string='') - returns a new hash object implementing the
10 given hash function; initializing the hash
11 using the given string data.
12
13Named constructor functions are also available, these are much faster
14than using new():
15
16md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
17
18More algorithms may be available on your platform but the above are
19guaranteed to exist.
20
Gregory P. Smithbde40072008-03-19 01:38:35 +000021NOTE: If you want the adler32 or crc32 hash functions they are available in
22the zlib module.
23
Georg Brandl7a4e8042006-10-29 18:01:08 +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.
Georg Brandl7a4e8042006-10-29 18:01:08 +000026
27Hash objects have these methods:
28 - update(arg): Update the hash object with the string arg. Repeated calls
29 are equivalent to a single call with the concatenation of all
30 the arguments.
31 - digest(): Return the digest of the strings passed to the update() method
32 so far. This may contain non-ASCII characters, including
33 NUL bytes.
34 - hexdigest(): Like digest() except the digest is returned as a string of
35 double length, containing only hexadecimal digits.
36 - copy(): Return a copy (clone) of the hash object. This can be used to
37 efficiently compute the digests of strings that share a common
38 initial substring.
39
40For example, to obtain the digest of the string 'Nobody inspects the
41spammish repetition':
42
43 >>> import hashlib
44 >>> m = hashlib.md5()
45 >>> m.update("Nobody inspects")
46 >>> m.update(" the spammish repetition")
47 >>> m.digest()
Gregory P. Smithf07e5a92008-08-31 16:34:18 +000048 '\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
Georg Brandl7a4e8042006-10-29 18:01:08 +000049
50More condensed:
51
52 >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest()
53 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
54
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000055"""
56
Gregory P. Smith99954c92009-08-16 21:54:45 +000057# This tuple and __get_builtin_constructor() must be modified if a new
58# always available algorithm is added.
59__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
60
61__all__ = __always_supported + ('new',)
62
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000063
64def __get_builtin_constructor(name):
65 if name in ('SHA1', 'sha1'):
66 import _sha
67 return _sha.new
68 elif name in ('MD5', 'md5'):
69 import _md5
70 return _md5.new
71 elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
72 import _sha256
73 bs = name[3:]
74 if bs == '256':
75 return _sha256.sha256
76 elif bs == '224':
77 return _sha256.sha224
78 elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
79 import _sha512
80 bs = name[3:]
81 if bs == '512':
82 return _sha512.sha512
83 elif bs == '384':
84 return _sha512.sha384
85
Gregory P. Smith99954c92009-08-16 21:54:45 +000086 raise ValueError('unsupported hash type %s' % name)
87
88
89def __get_openssl_constructor(name):
90 try:
91 f = getattr(_hashlib, 'openssl_' + name)
92 # Allow the C module to raise ValueError. The function will be
93 # defined but the hash not actually available thanks to OpenSSL.
94 f()
95 # Use the C function directly (very fast)
96 return f
97 except (AttributeError, ValueError):
98 return __get_builtin_constructor(name)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000099
100
101def __py_new(name, string=''):
102 """new(name, string='') - Return a new hashing object using the named algorithm;
103 optionally initialized with a string.
104 """
105 return __get_builtin_constructor(name)(string)
106
107
108def __hash_new(name, string=''):
109 """new(name, string='') - Return a new hashing object using the named algorithm;
110 optionally initialized with a string.
111 """
112 try:
113 return _hashlib.new(name, string)
114 except ValueError:
115 # If the _hashlib module (OpenSSL) doesn't support the named
116 # hash, try using our builtin implementations.
117 # This allows for SHA224/256 and SHA384/512 support even though
118 # the OpenSSL library prior to 0.9.8 doesn't provide them.
119 return __get_builtin_constructor(name)(string)
120
121
122try:
123 import _hashlib
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000124 new = __hash_new
Gregory P. Smith99954c92009-08-16 21:54:45 +0000125 __get_hash = __get_openssl_constructor
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000126except ImportError:
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000127 new = __py_new
Gregory P. Smith99954c92009-08-16 21:54:45 +0000128 __get_hash = __get_builtin_constructor
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000129
Gregory P. Smith99954c92009-08-16 21:54:45 +0000130for __func_name in __always_supported:
131 # try them all, some may not work due to the OpenSSL
132 # version not supporting that algorithm.
133 try:
134 globals()[__func_name] = __get_hash(__func_name)
135 except ValueError:
136 import logging
137 logging.exception('code for hash %s was not found.', __func_name)
138
139# Cleanup locals()
140del __always_supported, __func_name, __get_hash
141del __py_new, __hash_new, __get_openssl_constructor