How to Implement Password Hashing in Python
Password hashing is an essential technique used to protect user passwords by converting them into a secure, irreversible format. Instead of storing plain-text passwords, which is highly insecure, applications store the hashed version of the password.
Python provides several libraries for password hashing, with bcrypt and hashlib being the most commonly used. Among these, bcrypt is preferred for password storage because it includes salting and is resistant to brute-force attacks.
Why Hash Passwords?
Security: If your database is compromised, hashed passwords are difficult to reverse.
Irreversibility: A good hashing function does not allow retrieval of the original password.
Salting: Adding random data (a salt) makes each hash unique, even for identical passwords.
✅ Recommended Approach: Using bcrypt
Step 1: Install the bcrypt library
You can install it using pip:
pip install bcrypt
Step 2: Hash a password
import bcrypt
# Password to be hashed (must be bytes)
password = b"mysecretpassword"
# Generate salt and hash the password
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password, salt)
print("Hashed password:", hashed_password)
Step 3: Verify a password
# Input password to verify (must be bytes)
input_password = b"mysecretpassword"
# Compare the input password with the stored hash
if bcrypt.checkpw(input_password, hashed_password):
print("Password is correct!")
else:
print("Incorrect password.")
⚠️ Don't Do This: Avoid hashlib for password storage
While hashlib can hash strings (like SHA256 or SHA512), it lacks built-in salting and is faster—making it easier for attackers to crack passwords using brute-force or rainbow table attacks.
Example (not secure for passwords):
import hashlib
password = "mypassword".encode()
hashed = hashlib.sha256(password).hexdigest()
print(hashed)
✅ Use this only for non-security-sensitive data, not password storage.
Summary
Feature bcrypt hashlib
Salting ✅ Built-in ❌ Manual
Slow hashing (good) ✅ ❌ Too fast
Recommended for auth ✅ Yes ❌ No
Conclusion
For secure password storage in Python:
Always hash passwords before saving.
Use libraries like bcrypt that offer built-in salting and strong security.
Never store or compare passwords in plain text.
Learn Fullstack Python Training in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments