Skip to content

Instantly share code, notes, and snippets.

@reidrac
Created June 4, 2011 19:56
Show Gist options
  • Save reidrac/1008283 to your computer and use it in GitHub Desktop.
Save reidrac/1008283 to your computer and use it in GitHub Desktop.
Manage hash-salted passwords
from hashlib import sha1
from random import random, choice
class Password(object):
"""Manage hash-salted passwords."""
HASH = sha1
SALT_LEN = 24
HASHED_LEN = len(HASH().hexdigest()) + SALT_LEN
def __init__(self):
self.password = None
def _hash_password(self, password, salt):
"""Returns a hashed password."""
hashed = password
for i in range(1000):
hashed = self.HASH("%s%s" % (hashed, salt)).hexdigest()
return "%s%s" % (salt, hashed)
def set_password(self, password):
"""Stores the password in hashed form."""
salt = ''.join([choice(self.HASH("%s" % random()).hexdigest()) for i in range(self.SALT_LEN)])
self.password = self._hash_password(password, salt)
def check_password(self, password):
"""Compares the given password with the stored hashed form."""
hashed = self._hash_password(password, self.password[:self.SALT_LEN])
return self.password == hashed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment