Looking to store usernames and passwords in a database, and am wondering what the safest way to do so is. I know I have to use a salt somewhere, but am not sure how to generate it securely or how to apply it to encrypt the password. Some sample Python code would be greatly appreciated. Thanks.
+7
A:
Store the password+salt as a hash and the salt. Take a look at how django does it: basic docs and source.
In the db they store <type of hash>$<salt>$<hash>
in a single char field. You can also store the three parts in separate fields.
The function to set the password:
def set_password(self, raw_password):
import random
algo = 'sha1'
salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
hsh = get_hexdigest(algo, salt, raw_password)
self.password = '%s$%s$%s' % (algo, salt, hsh)
The get_hexdigest is just a thin wrapper around some hashing algorithms. You can use hashlib for that. Something like hashlib.sha1('%s%s' % (salt, hash)).hexdigest()
And the function to check the password:
def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return hsh == get_hexdigest(algo, salt, raw_password)
rz
2010-04-03 17:50:07
Do you have a link to the appropriate code file?
Justin Ethier
2010-04-03 17:51:45
This was really helpful. Thanks so much.
ensnare
2010-04-03 17:57:34
@justin ethier: there ya go. @ensnare: feel free to mark it as accepted ;-)
rz
2010-04-03 18:01:43
A:
If you have enough control over both endpoints of the application, the absolute best way is using SRP.
Paul Crowley
2010-04-07 10:46:24