Browse Source

Fix handling of unicode passwords (still using python2...)

Baptiste Jonglez 10 years ago
parent
commit
a0889d9528
1 changed files with 11 additions and 4 deletions
  1. 11 4
      coin/utils.py

+ 11 - 4
coin/utils.py

@@ -7,6 +7,7 @@ import binascii
 import base64
 import html2text
 import re
+import sys
 from datetime import date, timedelta
 from contextlib import contextmanager
 
@@ -31,11 +32,16 @@ def str_or_none(obj):
 
 def ldap_hash(password):
     """Hash a password for use with LDAP.  If the password is already hashed,
-    do nothing."""
+    do nothing.
+
+    Implementation details: Django provides us with a unicode object, so
+    we have to encode/decode it as needed to switch between unicode and
+    bytes.  The code should work fine with both python2 and python3.
+    """
     if password and not password.startswith('{SSHA}'):
         salt = binascii.hexlify(os.urandom(8))
-        digest = hashlib.sha1(password.encode() + salt).digest()
-        return '{SSHA}' + base64.b64encode(digest + salt).decode()
+        digest = hashlib.sha1(password.encode("utf-8") + salt).digest()
+        return '{SSHA}' + base64.b64encode(digest + salt).decode("utf-8")
     else:
         return password
 
@@ -144,4 +150,5 @@ def respects_language(fun):
     return _inner
 
 if __name__ == '__main__':
-    print(ldap_hash('coin'))
+    # ldap_hash expects an unicode string
+    print(ldap_hash(sys.argv[1].decode("utf-8")))