VMM/pycompat: Removed module hashlib. v0.7.x
authorPascal Volk <user@localhost.localdomain.org>
Sun, 04 Nov 2012 18:02:19 +0000
branchv0.7.x
changeset 636 27334cfc0c90
parent 635 54172669bbae
child 637 ca6621caff2f
VMM/pycompat: Removed module hashlib.
VirtualMailManager/password.py
VirtualMailManager/pycompat/hashlib.py
--- a/VirtualMailManager/password.py	Sat Nov 03 16:22:48 2012 +0000
+++ b/VirtualMailManager/password.py	Sun Nov 04 18:02:19 2012 +0000
@@ -15,22 +15,18 @@
         schemes, encodings = list_schemes()
 """
 
+import hashlib
+
 from crypt import crypt
 from random import SystemRandom
 from subprocess import Popen, PIPE
 
-try:
-    import hashlib
-except ImportError:
-    from VirtualMailManager.pycompat import hashlib
-
 from VirtualMailManager import ENCODING
 from VirtualMailManager.emailaddress import EmailAddress
 from VirtualMailManager.common import get_unicode, version_str
 from VirtualMailManager.constants import VMM_ERROR
 from VirtualMailManager.errors import VMMError
 
-COMPAT = hasattr(hashlib, 'compat')
 SALTCHARS = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
 PASSWDCHARS = '._-+#*23456789abcdefghikmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
 DEFAULT_B64 = (None, 'B64', 'BASE64')
@@ -81,33 +77,17 @@
 
 def _md4_new():
     """Returns an new MD4-hash object if supported by the hashlib or
-    provided by PyCrypto - other `None`.
+    provided by PyCrypto - otherwise `None`.
     """
     try:
         return hashlib.new('md4')
     except ValueError, err:
         if str(err) == 'unsupported hash type':
-            if not COMPAT:
-                try:
-                    from Crypto.Hash import MD4
-                    return MD4.new()
-                except ImportError:
-                    return None
-        else:
-            raise
-
-
-def _sha256_new(data=''):
-    """Returns a new sha256 object from the hashlib.
-
-    Returns `None` if the PyCrypto in pycompat.hashlib is too old."""
-    if not COMPAT:
-        return hashlib.sha256(data)
-    try:
-        return hashlib.new('sha256', data)
-    except ValueError, err:
-        if str(err) == 'unsupported hash type':
-            return None
+            try:
+                from Crypto.Hash import MD4
+                return MD4.new()
+            except ImportError:
+                return None
         else:
             raise
 
@@ -248,26 +228,22 @@
 
 def _sha256_hash(password, scheme, encoding):
     """Generates SHA256 hashes."""
-    sha256 = _sha256_new(password)
-    if sha256:
-        if encoding in DEFAULT_B64:
-            digest = sha256.digest().encode('base64').rstrip()
-        else:
-            digest = sha256.hexdigest()
-        return _format_digest(digest, scheme, encoding)
-    return _dovecotpw(password, scheme, encoding)
+    sha256 = hashlib.sha256(password)
+    if encoding in DEFAULT_B64:
+        digest = sha256.digest().encode('base64').rstrip()
+    else:
+        digest = sha256.hexdigest()
+    return _format_digest(digest, scheme, encoding)
 
 
 def _sha512_hash(password, scheme, encoding):
     """Generates SHA512 hashes."""
-    if not COMPAT:
-        sha512 = hashlib.sha512(password)
-        if encoding in DEFAULT_B64:
-            digest = sha512.digest().encode('base64').replace('\n', '')
-        else:
-            digest = sha512.hexdigest()
-        return _format_digest(digest, scheme, encoding)
-    return _dovecotpw(password, scheme, encoding)
+    sha512 = hashlib.sha512(password)
+    if encoding in DEFAULT_B64:
+        digest = sha512.digest().encode('base64').replace('\n', '')
+    else:
+        digest = sha512.hexdigest()
+    return _format_digest(digest, scheme, encoding)
 
 
 def _smd5_hash(password, scheme, encoding):
@@ -296,30 +272,25 @@
 
 def _ssha256_hash(password, scheme, encoding):
     """Generates SSHA256 (salted SHA256) hashes."""
-    sha256 = _sha256_new(password)
-    if sha256:
-        salt = _get_salt(SALTED_ALGO_SALT_LEN)
-        sha256.update(salt)
-        if encoding in DEFAULT_B64:
-            digest = (sha256.digest() + salt).encode('base64').rstrip()
-        else:
-            digest = sha256.hexdigest() + salt.encode('hex')
-        return _format_digest(digest, scheme, encoding)
-    return _dovecotpw(password, scheme, encoding)
+    sha256 = hashlib.sha256(password)
+    salt = _get_salt(SALTED_ALGO_SALT_LEN)
+    sha256.update(salt)
+    if encoding in DEFAULT_B64:
+        digest = (sha256.digest() + salt).encode('base64').rstrip()
+    else:
+        digest = sha256.hexdigest() + salt.encode('hex')
+    return _format_digest(digest, scheme, encoding)
 
 
 def _ssha512_hash(password, scheme, encoding):
     """Generates SSHA512 (salted SHA512) hashes."""
-    if not COMPAT:
-        salt = _get_salt(SALTED_ALGO_SALT_LEN)
-        sha512 = hashlib.sha512(password + salt)
-        if encoding in DEFAULT_B64:
-            digest = (sha512.digest() + salt).encode('base64').replace('\n',
-                                                                       '')
-        else:
-            digest = sha512.hexdigest() + salt.encode('hex')
-        return _format_digest(digest, scheme, encoding)
-    return _dovecotpw(password, scheme, encoding)
+    salt = _get_salt(SALTED_ALGO_SALT_LEN)
+    sha512 = hashlib.sha512(password + salt)
+    if encoding in DEFAULT_B64:
+        digest = (sha512.digest() + salt).encode('base64').replace('\n', '')
+    else:
+        digest = sha512.hexdigest() + salt.encode('hex')
+    return _format_digest(digest, scheme, encoding)
 
 _scheme_info = {
     'CLEARTEXT': (_clear_hash, 0x10000f00),
--- a/VirtualMailManager/pycompat/hashlib.py	Sat Nov 03 16:22:48 2012 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,58 +0,0 @@
-# -*- coding: UTF-8 -*-
-# Copyright (c) 2010 - 2012, Pascal Volk
-# See COPYING for distribution information.
-
-"""
-    VirtualMailManager.pycompat.hashlib
-
-    VirtualMailManager's minimal hashlib emulation for Python 2.4
-
-    hashlib.md5(...), hashlib.sha1(...), hashlib.new('md5', ...) and
-    hashlib.new('sha1', ...) will work always.
-
-    When the PyCrypto module <http://www.pycrypto.org/> could be found in
-    sys.path hashlib.new('md4', ...) will also work.
-
-    With PyCrypto >= 2.1.0alpha1 hashlib.new('sha256', ...) and
-    hashlib.sha256(...) becomes functional.
-"""
-
-
-import md5 as _md5
-import sha as _sha1
-
-try:
-    import Crypto
-except ImportError:
-    _md4 = None
-    SHA256 = None
-else:
-    from Crypto.Hash import MD4 as _md4
-    if hasattr(Crypto, 'version_info'):  # <- Available since v2.1.0alpha1
-        from Crypto.Hash import SHA256   # SHA256 works since v2.1.0alpha1
-        sha256 = SHA256.new
-    else:
-        SHA256 = None
-    del Crypto
-
-
-compat = 0x01
-md5 = _md5.new
-sha1 = _sha1.new
-
-
-def new(name, string=''):
-    """Return a new hashing object using the named algorithm, optionally
-    initialized with the provided string.
-    """
-    if name in ('md5', 'MD5'):
-        return _md5.new(string)
-    if name in ('sha1', 'SHA1'):
-        return _sha1.new(string)
-    if not _md4:
-        raise ValueError('unsupported hash type')
-    if name in ('md4', 'MD4'):
-        return _md4.new(string)
-    if name in ('sha256', 'SHA256') and SHA256:
-        return SHA256.new(string)
-    raise ValueError('unsupported hash type')