Start learning free

LESSON 23 OF 56 · SECURITY: CRYPTOGRAPHY FOR DEVELOPERS

Slow Hashes for Passwords in Python

Practice

SHA-256 is built to be fast. That's great for checking files and terrible for passwords: one graphics card computes billions of SHA-256 hashes a second, and every hash is a guess a thief gets to check. Worse, two people with the same password get the same hash.

The attack: with one round of SHA-256, a thief who copies the users table looks every hash up in a ready-made table of common passwords. Ana's and Ben's sunshine falls at once, and both accounts with it.

The fix: a slow, salted hash. hashlib.scrypt needs real time and 16 MB of memory for every try, and a random salt for each password makes equal passwords hash differently. Keep the salt and the costs in the stored text, so login can redo exactly the same work. Here is the same idea with another slow hash, PBKDF2:

salt = secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac("sha256", b"hunter2", salt, 600000)
stored = f"pbkdf2:600000:{salt.hex()}:{digest.hex()}"

The hidden check GET /check/stolen shows each stored hash's settings, looks it up in a table of common passwords, and looks for two users with the same hash:

POST /signup  {"email": "ana@example.com", "password": "sunshine"}  →  201  {"email": "ana@example.com"}
POST /signup  {"email": "ben@example.com", "password": "sunshine"}  →  201  {"email": "ben@example.com"}
POST /login  {"email": "ana@example.com", "password": "sunshine"}  →  200  {"email": "ana@example.com"}
POST /login  {"email": "ana@example.com", "password": "Sunshine"}  →  401  {"error": "Wrong email or password"}
GET /check/stolen  →  200  [{"email": "ana@example.com", "settings": "scrypt:16384:8:1", "cracked": null, "same_hash_as": null}, …]

Your task: signup and login already call two functions that don't exist yet. Write hash_password(password): a 16-byte random salt, hashlib.scrypt with the costs N, R and P, and one returned text scrypt:N:R:P:salt:digest with the salt and digest in hex. Then write check_password(stored, password): split the text, redo scrypt with the stored salt and costs, and compare with hmac.compare_digest.


Assignment
Follow the Coding Tutorial to hash passwords with scrypt and a random salt, and to check them at login.


Hint
Pass the salt and the costs to hashlib.scrypt by name: salt=, n=, r=, p=. At login, bytes.fromhex and int turn the stored texts back into bytes and numbers.


STEP 1 OF 8
    Ctrl + Enter to check

    Secx Scrypt in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free