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.
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).
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.
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.
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/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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With