Commits

Kelvin Wong committed 9a43fef Draft

Clean linefeeds from legacy hashes

Comments (0)

Files changed (1)

django_scrypt/hashers.py

 """
 from __future__ import unicode_literals
 import sys
+import base64
 from django.contrib.auth.hashers import BasePasswordHasher, mask_hash
 from django.utils.datastructures import SortedDict
 from django.utils.crypto import constant_time_compare
 PYTHON3 = sys.version_info >= (3, 0)
 
 
-def base64(s):
-    """Returns Base64 encoded bytes"""
-    if PYTHON3:
-        import base64
-        return base64.encodestring(s)
-    else:
-        return s.encode('base64')
+def enbase64(s):
+    """Returns Base64 encoded bytes without linefeeds"""
+    return base64.b64encode(s)
+
+
+def debase64(s):
+    """Decodes Base64 encoded bytes with or without linefeeds"""
+    if PYTHON3 and isinstance(s, str):
+        s = bytes(s, 'utf-8')
+    return base64.b64decode(s)
 
 
 def stringify(s):
             return str(s).strip()
 
 
+def clean_base64_scrypt_hash(hash):
+    """Cleans the Base64 fragment of linefeeds"""
+    algorithm, salt, Nexp, r, p, buflen, h = hash.split('$')
+    h = enbase64(debase64(h))
+    hash = "$".join([algorithm, salt, Nexp, r, p, buflen, stringify(h)])
+    return hash
+
+
 class ScryptPasswordHasher(BasePasswordHasher):
     """
     A secure password hasher using the Scrypt algorithm
 
         """
         assert encoded
-        encoded = encoded.strip()
+        encoded = clean_base64_scrypt_hash(encoded)
         algorithm, salt, Nexp, r, p, buflen, h = encoded.split('$')
         assert algorithm == self.algorithm
         # TODO: buflen is an experimental proposal in py-scrypt
         hashed.append(str(p))
         hashed.append(str(buflen))
         h = scrypt.hash(password, salt, 2 ** Nexp, r, p)
-        hashed.append(stringify(base64(h)))
+        hashed.append(stringify(enbase64(h)))
         return "$".join(hashed)
 
     def safe_summary(self, encoded):
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.