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.
A cryptographic hash function is a one-way function:
+-------------------+ Cryptographic Algorithm +-------------------------------------+ | Plaintext Password| =====================================> | Salted Hash Digest | | "SecretP@ss2026!" | (PBKDF2-HMAC-SHA256 + 16-byte salt) | "pbkdf2:sha256:600000$8xG...$9mP..." | +-------------------+ +-------------------------------------+
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!
generate_password_hashcheck_password_hashWhen 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.
Encapsulate password handling directly on your SQLAlchemy User model using Python properties:
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?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Database Schema Migrations with Flask-Migrate | User Session Management with Flask-Login |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.