1 # -*- coding: UTF-8 -*- |
|
2 # Copyright (c) 2010 - 2014, Pascal Volk |
|
3 # See COPYING for distribution information. |
|
4 |
|
5 """ |
|
6 VirtualMailManager.pycompat.hashlib |
|
7 |
|
8 VirtualMailManager's minimal hashlib emulation for Python 2.4 |
|
9 |
|
10 hashlib.md5(...), hashlib.sha1(...), hashlib.new('md5', ...) and |
|
11 hashlib.new('sha1', ...) will work always. |
|
12 |
|
13 When the PyCrypto module <http://www.pycrypto.org/> could be found in |
|
14 sys.path hashlib.new('md4', ...) will also work. |
|
15 |
|
16 With PyCrypto >= 2.1.0alpha1 hashlib.new('sha256', ...) and |
|
17 hashlib.sha256(...) becomes functional. |
|
18 """ |
|
19 |
|
20 |
|
21 import md5 as _md5 |
|
22 import sha as _sha1 |
|
23 |
|
24 try: |
|
25 import Crypto |
|
26 except ImportError: |
|
27 _md4 = None |
|
28 SHA256 = None |
|
29 else: |
|
30 from Crypto.Hash import MD4 as _md4 |
|
31 if hasattr(Crypto, 'version_info'): # <- Available since v2.1.0alpha1 |
|
32 from Crypto.Hash import SHA256 # SHA256 works since v2.1.0alpha1 |
|
33 sha256 = SHA256.new |
|
34 else: |
|
35 SHA256 = None |
|
36 del Crypto |
|
37 |
|
38 |
|
39 compat = 0x01 |
|
40 md5 = _md5.new |
|
41 sha1 = _sha1.new |
|
42 |
|
43 |
|
44 def new(name, string=''): |
|
45 """Return a new hashing object using the named algorithm, optionally |
|
46 initialized with the provided string. |
|
47 """ |
|
48 if name in ('md5', 'MD5'): |
|
49 return _md5.new(string) |
|
50 if name in ('sha1', 'SHA1'): |
|
51 return _sha1.new(string) |
|
52 if not _md4: |
|
53 raise ValueError('unsupported hash type') |
|
54 if name in ('md4', 'MD4'): |
|
55 return _md4.new(string) |
|
56 if name in ('sha256', 'SHA256') and SHA256: |
|
57 return SHA256.new(string) |
|
58 raise ValueError('unsupported hash type') |
|