3 # Copyright (C) 2005 Gregory P. Smith (greg@electricrain.com)
4 # Licensed to PSF under a Contributor Agreement.
7 __doc__
= """hashlib module - A common interface to many hash functions.
9 new(name, string='') - returns a new hash object implementing the
10 given hash function; initializing the hash
11 using the given string data.
13 Named constructor functions are also available, these are much faster
16 md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
18 More algorithms may be available on your platform but the above are
21 Choose your hash function wisely. Some have known weaknesses.
22 sha384 and sha512 will be slow on 32 bit platforms.
26 def __get_builtin_constructor(name
):
27 if name
in ('SHA1', 'sha1'):
30 elif name
in ('MD5', 'md5'):
33 elif name
in ('SHA256', 'sha256', 'SHA224', 'sha224'):
40 elif name
in ('SHA512', 'sha512', 'SHA384', 'sha384'):
48 raise ValueError, "unsupported hash type"
51 def __py_new(name
, string
=''):
52 """new(name, string='') - Return a new hashing object using the named algorithm;
53 optionally initialized with a string.
55 return __get_builtin_constructor(name
)(string
)
58 def __hash_new(name
, string
=''):
59 """new(name, string='') - Return a new hashing object using the named algorithm;
60 optionally initialized with a string.
63 return _hashlib
.new(name
, string
)
65 # If the _hashlib module (OpenSSL) doesn't support the named
66 # hash, try using our builtin implementations.
67 # This allows for SHA224/256 and SHA384/512 support even though
68 # the OpenSSL library prior to 0.9.8 doesn't provide them.
69 return __get_builtin_constructor(name
)(string
)
74 # use the wrapper of the C implementation
77 for opensslFuncName
in filter(lambda n
: n
.startswith('openssl_'), dir(_hashlib
)):
78 funcName
= opensslFuncName
[len('openssl_'):]
80 # try them all, some may not work due to the OpenSSL
81 # version not supporting that algorithm.
82 f
= getattr(_hashlib
, opensslFuncName
)
84 # Use the C function directly (very fast)
85 exec funcName
+ ' = f'
88 # Use the builtin implementation directly (fast)
89 exec funcName
+ ' = __get_builtin_constructor(funcName)'
91 # this one has no builtin implementation, don't define it
99 # We don't have the _hashlib OpenSSL module?
100 # use the built in legacy interfaces via a wrapper function
103 # lookup the C function to use directly for the named constructors
104 md5
= __get_builtin_constructor('md5')
105 sha1
= __get_builtin_constructor('sha1')
106 sha224
= __get_builtin_constructor('sha224')
107 sha256
= __get_builtin_constructor('sha256')
108 sha384
= __get_builtin_constructor('sha384')
109 sha512
= __get_builtin_constructor('sha512')