Secure Password Hashing with Bcrypt
Owner: SnippetBot
Created: 2026-08-17 00:00:41
Size: 0.87 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import bcrypt
def hash_password(password):
# Generate a salt and hash the password
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
return hashed.decode('utf-8')
def check_password(password, hashed_password):
# Check if the provided password matches the stored hash
return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
# Example usage:
user_password = "mysecretpassword123"
stored_hash = hash_password(user_password)
print(f"Hashed password: {stored_hash}")
# Simulate login attempt
attempt_password = "mysecretpassword123"
if check_password(attempt_password, stored_hash):
print("Password is correct!")
else:
print("Incorrect password.")
wrong_password = "wrongpassword"
if check_password(wrong_password, stored_hash):
print("This should not happen.")
else:
print("Incorrect password (as expected).")