Fix the tag.
[python/dscho.git] / Lib / hashlib.py
blobefe66ec600d9312fd8914d71fa1e0e75ebd144b9
1 # $Id$
3 # Copyright (C) 2005-2007 Gregory P. Smith (greg@krypto.org)
4 # Licensed to PSF under a Contributor Agreement.
7 __doc__ = """hashlib module - A common interface to many hash functions.
9 new(name, data=b'') - returns a new hash object implementing the
10 given hash function; initializing the hash
11 using the given binary data.
13 Named constructor functions are also available, these are faster
14 than using new(name):
16 md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
18 More algorithms may be available on your platform but the above are
19 guaranteed to exist.
21 NOTE: If you want the adler32 or crc32 hash functions they are available in
22 the zlib module.
24 Choose your hash function wisely. Some have known collision weaknesses.
25 sha384 and sha512 will be slow on 32 bit platforms.
27 Hash objects have these methods:
28 - update(arg): Update the hash object with the bytes in 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 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.
35 - 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.
39 For example, to obtain the digest of the string 'Nobody inspects the
40 spammish repetition':
42 >>> import hashlib
43 >>> m = hashlib.md5()
44 >>> m.update(b"Nobody inspects")
45 >>> m.update(b" the spammish repetition")
46 >>> m.digest()
47 b'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
49 More condensed:
51 >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
52 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
54 """
57 def __get_builtin_constructor(name):
58 if name in ('SHA1', 'sha1'):
59 import _sha1
60 return _sha1.sha1
61 elif name in ('MD5', 'md5'):
62 import _md5
63 return _md5.md5
64 elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
65 import _sha256
66 bs = name[3:]
67 if bs == '256':
68 return _sha256.sha256
69 elif bs == '224':
70 return _sha256.sha224
71 elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
72 import _sha512
73 bs = name[3:]
74 if bs == '512':
75 return _sha512.sha512
76 elif bs == '384':
77 return _sha512.sha384
79 raise ValueError("unsupported hash type")
82 def __py_new(name, data=b''):
83 """new(name, data=b'') - Return a new hashing object using the named algorithm;
84 optionally initialized with data (which must be bytes).
85 """
86 return __get_builtin_constructor(name)(data)
89 def __hash_new(name, data=b''):
90 """new(name, data=b'') - Return a new hashing object using the named algorithm;
91 optionally initialized with data (which must be bytes).
92 """
93 try:
94 return _hashlib.new(name, data)
95 except ValueError:
96 # If the _hashlib module (OpenSSL) doesn't support the named
97 # hash, try using our builtin implementations.
98 # This allows for SHA224/256 and SHA384/512 support even though
99 # the OpenSSL library prior to 0.9.8 doesn't provide them.
100 return __get_builtin_constructor(name)(data)
103 try:
104 import _hashlib
105 # use the wrapper of the C implementation
106 new = __hash_new
108 for opensslFuncName in filter(lambda n: n.startswith('openssl_'), dir(_hashlib)):
109 funcName = opensslFuncName[len('openssl_'):]
110 try:
111 # try them all, some may not work due to the OpenSSL
112 # version not supporting that algorithm.
113 f = getattr(_hashlib, opensslFuncName)
115 # Use the C function directly (very fast)
116 exec(funcName + ' = f')
117 except ValueError:
118 try:
119 # Use the builtin implementation directly (fast)
120 exec(funcName + ' = __get_builtin_constructor(funcName)')
121 except ValueError:
122 # this one has no builtin implementation, don't define it
123 pass
124 # clean up our locals
125 del f
126 del opensslFuncName
127 del funcName
129 except ImportError:
130 # We don't have the _hashlib OpenSSL module?
131 # use the built in legacy interfaces via a wrapper function
132 new = __py_new
134 # lookup the C function to use directly for the named constructors
135 md5 = __get_builtin_constructor('md5')
136 sha1 = __get_builtin_constructor('sha1')
137 sha224 = __get_builtin_constructor('sha224')
138 sha256 = __get_builtin_constructor('sha256')
139 sha384 = __get_builtin_constructor('sha384')
140 sha512 = __get_builtin_constructor('sha512')