Password Hashing with Werkzeug Security
Password Hashing with Werkzeug Security
Storing plaintext passwords in a database is one of the most catastrophic security failures a web developer can make. If a database is breached or leaked, plaintext passwords immediately compromise user accounts across every service where they reuse that password.
Werkzeug provides cryptographic password hashing via its werkzeug.security module, utilizing salted PBKDF2 or scrypt algorithms.
1. How Cryptographic Hashing Works
A cryptographic hash function is a one-way function:
- Given an input password, it produces a fixed-length hexadecimal digest.
- It is mathematically infeasible to reverse-engineer the original password from the digest.
+-------------------+ Cryptographic Algorithm +-------------------------------------+ | Plaintext Password| =====================================> | Salted Hash Digest | | "SecretP@ss2026!" | (PBKDF2-HMAC-SHA256 + 16-byte salt) | "pbkdf2:sha256:600000$8xG...$9mP..." | +-------------------+ +-------------------------------------+
The Role of Salt:
A salt is a cryptographically random byte string generated for every individual password before hashing. Salts prevent rainbow table attacks (precomputed hash lookup tables) and ensure that two users with identical passwords will have completely different hashes!
2. Generating Hashes with generate_password_hash
3. Verifying Passwords with check_password_hash
When a user attempts to log in, never attempt to decrypt the stored hash. Instead, pass the entered password and the stored hash into check_password_hash():
check_password_hash extracts the salt and algorithm parameters from the stored hash string, hashes the entered password using those exact parameters, and uses a constant-time comparison algorithm to prevent timing attacks.
4. Integrating Password Hashing into a User Model
Encapsulate password handling directly on your SQLAlchemy User model using Python properties:
Usage in Registration & Login:
Practice Quiz
werkzeug.security manage password security in Flask?user.password raise an AttributeError in the recommended User model pattern?check_password_hash use a constant-time comparison algorithm?User Session Management with Flask-Login
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Database Schema Migrations with Flask-Migrate | User Session Management with Flask-Login |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.