Python's safest method to store and retrieve passwords from a database Python's safest method to store and retrieve passwords from a database python python

Python's safest method to store and retrieve passwords from a database


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)


I think it is best to use a function dedicated to hashing passwords for this. I explain some reasons for this here: https://stackoverflow.com/a/10948614/893857Nowadays the standard library has a dedicated section in the documentation for hashing password. It even mentions that you should get your salt from a cryptographically secure random source like os.urandom().


I answered this here: https://stackoverflow.com/a/18488878/1661689, and so did @Koffie.

I don't know how to emphasize enough that the accepted answer is NOT secure. It is better than plain text, and better than an unsalted hash, but it is still extremely vulnerable to dictionary and even brute-force attacks. Instead, please use a SLOW KDF like bcrypt (or at least PBKDF2 with 10,000 iterations)