Hash Passwords Safely
Exit

Hash Passwords Safely

Add password hashing and verification functions using bcrypt

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Why hashing matters

If someone gains access to your database, they can read every row in every table. Without hashing, that includes every user's password in plain text.

A hash is a one-way transformation. You can turn "secret123" into a long string of characters, but you cannot reverse it back to "secret123". Even the server cannot recover the original password from the hash.

Why bcrypt

Bcrypt is the industry standard for password hashing. It is deliberately slow — each hash takes about 100 milliseconds. That speed is unnoticeable during a single login, but it makes brute-force attacks impractical. An attacker trying millions of password guesses would need years instead of seconds.

Two functions

You need two functions that work as a pair:

  • hash_password: takes a plain text password and returns a bcrypt hash. You call this during registration.
  • verify_password: takes a plain text password and a stored hash, then checks if they match. You call this during login.

The CryptContext object from passlib handles all the bcrypt details. You configure it once and call its .hash() and .verify() methods.

Instructions

Add password hashing functions to auth.py.

  1. Create a CryptContext called pwd_context with schemes=["bcrypt"] and deprecated="auto" — this configures passlib to use bcrypt for all password operations.
  2. Define a function called hash_password that takes a password string and returns pwd_context.hash(password).
  3. Define a function called verify_password that takes plain_password and hashed_password strings and returns pwd_context.verify(plain_password, hashed_password).