Hashing, encoding and basic security · 3 / 15 Theory

Storing passwords correctly

If a database leaks, whatever is stored in it is exposed. Passwords must be stored so that, even with the database in an attacker's hands, recovering them is very costly.

import hashlib, hmac

# BAD: storing the password, or its simple hash
print(hashlib.sha256(b"123456").hexdigest()[:16])    # 8d969eef6ecad3c2  the same for every user

# BETTER: slow derivation with a different salt per user
def derive(password, salt, rounds=100_000):
    return hashlib.pbkdf2_hmac("sha256", password.encode(), salt, rounds)

salt_ana = b"salt-of-ana-0001"          # in practice: os.urandom(16), stored next to the hash
salt_luis = b"salt-of-luis-0002"
h1 = derive("123456", salt_ana)
h2 = derive("123456", salt_luis)
print(h1 == h2)                       # False: same password, different fingerprint
print(len(h1))                        # 32

def check(password, salt, stored):
    return hmac.compare_digest(derive(password, salt), stored)

print(check("123456", salt_ana, h1))       # True
print(check("1234567", salt_ana, h1))      # False

import os
print(len(os.urandom(16)))            # 16 cryptographic random bytes
  • Never store the password in plain text, or reversibly encrypted, or with a fast unsalted hash (there are tables with billions of precomputed hashes).
  • The salt is a random value, different for each user, stored next to the fingerprint. It makes two equal passwords give different fingerprints and makes precomputed tables useless.
  • A slow function (pbkdf2_hmac with many rounds, scrypt, or packages such as argon2) makes every attacker guess more expensive. With hundreds of thousands of rounds, trying millions of passwords is no longer instant.
  • To log in, recompute with the stored salt and compare with compare_digest. A password cannot be “recovered”: if forgotten, it is reset.

You practice it in Store passwords with salt.