0
0
Flaskframework~5 mins

Password hashing with Werkzeug in Flask

Choose your learning style9 modes available
Introduction

Password hashing helps keep user passwords safe by turning them into secret codes that are hard to guess or reverse.

When you want to store user passwords safely in a database.
When you need to check if a user's entered password matches the stored one without saving the actual password.
When building login or registration features in a web app.
When you want to protect user data from hackers if your database is leaked.
Syntax
Flask
from werkzeug.security import generate_password_hash, check_password_hash

hashed_password = generate_password_hash('your_password')
is_correct = check_password_hash(hashed_password, 'user_input_password')

generate_password_hash creates a safe hashed version of the password.

check_password_hash compares a hashed password with a user input to verify if they match.

Examples
Creates a hashed password from the string 'mypassword'.
Flask
hashed = generate_password_hash('mypassword')
Checks if the hashed password matches the original password.
Flask
check_password_hash(hashed, 'mypassword')  # returns True
Returns False because the password does not match.
Flask
check_password_hash(hashed, 'wrongpassword')  # returns False
Sample Program

This program hashes a password, then checks if a user input matches it. It prints the hashed password and whether the input is correct.

Flask
from werkzeug.security import generate_password_hash, check_password_hash

# Create a hashed password
hashed_pw = generate_password_hash('secret123')
print(f'Hashed password: {hashed_pw}')

# Simulate user input
user_input = 'secret123'

# Check if user input matches the hashed password
if check_password_hash(hashed_pw, user_input):
    print('Password is correct!')
else:
    print('Password is incorrect!')
OutputSuccess
Important Notes

Never store plain text passwords; always hash them before saving.

Werkzeug uses strong hashing algorithms by default, so you don't need to choose one manually.

Hashed passwords include a random salt, so the same password will have different hashes each time.

Summary

Password hashing keeps passwords safe by turning them into secret codes.

Use generate_password_hash to hash passwords and check_password_hash to verify them.

Always hash passwords before storing to protect user data.