Encryption Recommendation
Tim Chase
python.list at tim.thechases.com
Mon Jan 28 11:23:14 EST 2008
> Usually, one doesn't store clear-text passwords. Instead, use a
> hash-algorithm like md5 or crypt (the former is in the standard lib, don't
> know of the other out of my head) and hash the password, and store that
> hash.
Python offers md5, and SHA modules built-in. (yay, python!)
http://docs.python.org/lib/module-md5.html
http://docs.python.org/lib/module-sha.html
It does also offer access to the crypt() function on Unix-like
OS'es but not Win32:
http://docs.python.org/lib/module-crypt.html
but it's based on DES which is no longer considered particularly
secure. From what I've seen, even MD5 is being phased out in
favor of SHA.
> If a user enters the password, use the same algorithm, and compare the
> resulting hashes with the stored one.
Generally one adds a "salt" to the mix, a random piece of data
that's stored with the password, so that if two users use the
same password, the salt makes them the appear like different
passwords:
import sha
import string
from random import choice
SALT_CHAR_COUNT = 5
salt_chars = string.letters +
string.numbers +
string.punctuation
def is_valid(username, password):
correct_hash, salt = get_hash_and_salt(username)
test_hash = sha.new(salt + password).hexdigest()
return test_hash == correct_hash
def set_password(username, password):
salt = ''.join([random.choice(salt_chars)
for _ in xrange(SALT_CHAR_COUNT)])
hash = sha.new(salt + password)
save_user(username, salt, hash)
Implementing get_hash_and_salt() and save_user() (and perhaps
tweaking the desired set of salt_chars) are left as an exercise
to the reader, using whatever persistent storage mechanism suits.
-tkc
More information about the Python-list
mailing list