Skip to content

Instantly share code, notes, and snippets.

Created October 12, 2010 16:59
Show Gist options
  • Save fwenzel/622519 to your computer and use it in GitHub Desktop.
Save fwenzel/622519 to your computer and use it in GitHub Desktop.
Monkey-patching stronger hash support into Django
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()
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.
AUTHENTICATION_BACKENDS = ('myapp.auth.Sha256Backend',)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment