Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 215
ensnare Avatar asked Apr 03 '10 17:04

ensnare


People also ask

What practices best to store passwords in a database?

Using cryptographic hash function is better than storing plain text password. Hackers are smart guys and once they came to know that developers are storing hashed passwords, they pre-computed hash of large number of words (from a popular word list or dictionary words).

What is the most secured methodology to store a password?

Hashing and Salting This technique is considered one of the most secure nowadays. Is adding “something” (a salt) and hashing it along with the user's password.

How do you secure database credentials in Python?

Store the credentials in a config file and use AWS KMS decryption to encrypt the password. You may store the KMS decrypted long blob/string in the config file. More secure than the previous one but still not highly secure. Configure the credentials as environmental variables and access them from the script.


2 Answers

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) 
like image 118
rz. Avatar answered Sep 29 '22 14:09

rz.


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/893857 Nowadays 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().

like image 45
M.D. Avatar answered Sep 29 '22 14:09

M.D.