How to Implement Password Hashing in Python

 πŸ” What is Password Hashing?

Password hashing converts a plain text password into a fixed, scrambled string using a one-way function. This helps store passwords securely — even if someone accesses the database, they can't easily get the original password.


✅ Recommended Library: bcrypt

bcrypt is a popular Python library for hashing passwords. It’s secure and easy to use.


πŸ”§ Step-by-Step Guide

1. Install bcrypt (if not already installed):

bash

Copy

Edit

pip install bcrypt

2. Hash a Password

python

Copy

Edit

import bcrypt


# Plain text password (e.g., from user input)

password = "my_secure_password"


# Convert to bytes

password_bytes = password.encode('utf-8')


# Generate a salt and hash the password

hashed = bcrypt.hashpw(password_bytes, bcrypt.gensalt())


print("Hashed password:", hashed)

πŸ” The result will look like:

b'$2b$12$wVQKqG5yUVz7UZRxrI5YDeSR2Tu5RAuPcv8ya8Y1BzN.9EOgJ5Vpu'


3. Verify a Password (Login Scenario)

python

Copy

Edit

# User enters password during login

entered_password = "my_secure_password"

entered_password_bytes = entered_password.encode('utf-8')


# Check if the entered password matches the stored hash

if bcrypt.checkpw(entered_password_bytes, hashed):

    print("Password is correct!")

else:

    print("Password is incorrect.")

⚠️ Important Tips

Always store only the hashed password in your database — never plain text.


Do not try to "decrypt" a hash. Hashing is a one-way process.


Use a unique salt (bcrypt handles this for you) to protect against rainbow table attacks.


πŸ“Œ Summary

Action Code

Hash password bcrypt.hashpw()

Verify password bcrypt.checkpw()

Store in DB Store the output of hashpw() as bytes or string

Learn Full Stack Python Course in Hyderabad

Read More

Understanding OAuth2 in Full Stack Python Applications

Building Secure Login and Registration Systems with Python

Understanding CSRF Protection in Django for Full Stack Python Apps

Full Stack Python: Protecting Your Application from SQL Injection

Visit Our IHUB Talent Training Institute in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Tosca for API Testing: A Step-by-Step Tutorial

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing