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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
I think it is best to use a package dedicated to hashing passwords for this like passlib: http://packages.python.org/passlib/ for reasons as I explained here: https://stackoverflow.com/a/10948614/893857
If you have enough control over both endpoints of the application, the absolute best way is using PAK-Z+.
(Edited: the original version recommended SRP but PAK-Z+ has a proof of security.)
Here is a simpler way (taken from effbot), provided passwords with a length greater than 8 will not be a problem*:
for generate the password :
*: A password with a length greater than 8 is stripped from the right down to 8 chars long
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:
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:
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)