Created
October 12, 2010 16:59
-
-
Save fwenzel/622519 to your computer and use it in GitHub Desktop.
Monkey-patching stronger hash support into Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
from future import django_sha256_support | |
Monkey-patch SHA-256 support into Django's auth system. If Django ticket #5600 | |
ever gets fixed, this can be removed. | |
""" | |
import hashlib | |
import random | |
import os | |
from django.contrib.auth import models as auth_models | |
from django.contrib.auth.backends import ModelBackend | |
def get_hexdigest(algorithm, salt, raw_password): | |
"""Generate SHA-256 hash.""" | |
if algorithm == 'sha256': | |
return hashlib.sha256(salt + raw_password).hexdigest() | |
else: | |
return get_hexdigest_old(algorithm, salt, raw_password) | |
get_hexdigest_old = auth_models.get_hexdigest | |
auth_models.get_hexdigest = get_hexdigest | |
def set_password(self, raw_password): | |
"""Set SHA-256 password.""" | |
algo = 'sha256' | |
salt = os.urandom(5).encode('hex') # Random, 10-digit (hex) salt. | |
hsh = get_hexdigest(algo, salt, raw_password) | |
self.password = '$'.join((algo, salt, hsh)) | |
auth_models.User.set_password = set_password | |
class Sha256Backend(ModelBackend): | |
""" | |
Overriding the Django model backend without changes ensures our | |
monkeypatching happens by the time we import auth. | |
""" | |
pass |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AUTHENTICATION_BACKENDS = ('myapp.auth.Sha256Backend',) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment