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.
- Create a
CryptContextcalledpwd_contextwithschemes=["bcrypt"]anddeprecated="auto"— this configures passlib to use bcrypt for all password operations. - Define a function called
hash_passwordthat takes apasswordstring and returnspwd_context.hash(password). - Define a function called
verify_passwordthat takesplain_passwordandhashed_passwordstrings and returnspwd_context.verify(plain_password, hashed_password).
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding