32

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.

Magnus Hoff
  • 20,105
  • 8
  • 58
  • 81
ensnare
  • 34,050
  • 49
  • 140
  • 211

5 Answers5

40

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)
NilsFK
  • 7
  • 1
  • 3
rz.
  • 18,901
  • 10
  • 51
  • 47
  • This was really helpful. Thanks so much. – ensnare Apr 03 '10 at 17:57
  • Could be better - you don't use a constant time string compare (not so important here, but if the user does the hashing, for example secure cookies, then you must use constant time string compare), and sha1 can be brute forced for predictable (i.e. most people's) passwords. – wisty Jun 29 '11 at 14:24
  • 1
    These functions are class functions, but the OP did not ask for class functions. – micsthepick May 26 '16 at 03:24
16

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

Community
  • 1
  • 1
M.D.
  • 1,086
  • 9
  • 18
15

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)

Community
  • 1
  • 1
Terrel Shumway
  • 726
  • 7
  • 8
  • Are you suggesting that storing correctly salted, hashed passwords is an **extremely vulnerable** practice? You can't use a dictionary attack on salted hashes. – vroomfondel Aug 28 '13 at 18:05
  • 3
    No. I am suggesting that a single iteration of SHA-1, as the code above suggests, is not "correctly salted and hashed". You *can* use a dictionary attack on salted hashes, and the faster the hash, the faster each pw can be tried. Would you rather it took one day or 64,000 days for the attack to succeed? SHA-x hashing is *very* fast on custom hardware (ASICs). https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet#Impose_infeasible_verification_on_attacker http://stackoverflow.com/questions/13545677/python-passlib-what-is-the-best-value-for-rounds – Terrel Shumway Aug 29 '13 at 04:55
  • 1
    @rz says "take a look at how Django does it" and then shows code that is completely different. Django *does* do it correctly: https://github.com/django/django/blob/master/django/contrib/auth/hashers.py#L216 – Terrel Shumway Aug 29 '13 at 05:14
3

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.)

Paul Crowley
  • 1,544
  • 12
  • 22
0

Here is a simpler way (taken from effbot), provided passwords with a length greater than 8 will not be a problem*:

import crypt

import random, string

def getsalt(chars = string.letters + string.digits):
    # generate a random 2-character 'salt'
    return random.choice(chars) + random.choice(chars)

for generate the password :

crypt.crypt("password", getsalt())

*: A password with a length greater than 8 is stripped from the right down to 8 chars long

micsthepick
  • 545
  • 5
  • 19
llazzaro
  • 3,380
  • 3
  • 29
  • 46