MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Password Hashing with Werkzeug Security0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
6.1Password Hashing with Werkzeug Security6.2User Session Management with Flask-Login6.3Role-Based Access Control & Custom Decorators
HomeTutorialsFlaskPassword Hashing with Werkzeug Security
User Session Management with Flask-Login

Password Hashing with Werkzeug Security

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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.
Visual Architecture Blueprint
+-------------------+        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

1from werkzeug.security import generate_password_hash, check_password_hash
2 
3# Hash a plaintext password
4plaintext = "SuperSecretPassword123"
5hashed_password = generate_password_hash(
6 plaintext,
7 method="pbkdf2:sha256:600000", # Algorithm and iteration work factor
8 salt_length=16
9)
10 
11print(hashed_password)
12# Output format: method$salt$hash
13# Example: 'pbkdf2:sha256:600000$hK4J8vL2...$8f4a7c1b...'

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():

1entered_password = "SuperSecretPassword123"
2 
3# Returns True if password matches; False otherwise
4is_valid = check_password_hash(hashed_password, entered_password)
5 
6if is_valid:
7 print("Authentication successful!")
8else:
9 print("Invalid credentials.")

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:

1from flask_sqlalchemy import SQLAlchemy
2from werkzeug.security import generate_password_hash, check_password_hash
3 
4db = SQLAlchemy()
5 
6class User(db.Model):
7 __tablename__ = "users"
8 
9 id = db.Column(db.Integer, primary_key=True)
10 username = db.Column(db.String(50), unique=True, nullable=False)
11 email = db.Column(db.String(120), unique=True, nullable=False)
12
13 # Store only the hashed string, NEVER the plaintext password!
14 password_hash = db.Column(db.String(256), nullable=False)
15 
16 @property
17 def password(self):
18 # Prevent reading password attribute directly
19 raise AttributeError("password is not a readable attribute")
20 
21 @password.setter
22 def password(self, plaintext_password):
23 # Automatically hashes password when setting user.password = "secret"
24 self.password_hash = generate_password_hash(plaintext_password)
25 
26 def verify_password(self, plaintext_password):
27 # Instance method to verify login credentials
28 return check_password_hash(self.password_hash, plaintext_password)

Usage in Registration & Login:

1# Registration
2new_user = User(username="sumit", email="sumit@example.com")
3new_user.password = "StrongPass2026!" # Automatically hashed!
4db.session.add(new_user)
5db.session.commit()
6 
7# Login Verification
8user = User.query.filter_by(username="sumit").first()
9if user and user.verify_password("StrongPass2026!"):
10 # Log user in
11 pass

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Which two functions from werkzeug.security manage password security in Flask?
Question 2
Why is a random "salt" added to passwords before hashing?
Question 3
Why does attempting to read user.password raise an AttributeError in the recommended User model pattern?
Question 4
Why does check_password_hash use a constant-time comparison algorithm?
Question 5
Can a properly generated cryptographic hash be decrypted back into the original plaintext password?
Next Lesson

User Session Management with Flask-Login

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Database Schema Migrations with Flask-MigrateUser Session Management with Flask-Login

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext