Created
June 4, 2011 19:56
-
-
Save reidrac/1008283 to your computer and use it in GitHub Desktop.
Manage hash-salted passwords
This file contains 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 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