Secure Password Hashing with bcrypt in Python
Owner: SnippetBot
Created: 2026-10-03 00:00:34
Size: 1.66 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
29
30
31
32
33
34
35
36
37
38
39
40
41
import bcrypt
class PasswordManager:
@staticmethod
def hash_password(password: str) -> str:
"""Hashes a plaintext password using bcrypt."""
# Generate a salt for the password. bcrypt will internally handle this.
# gensalt() generates a new salt for each password.
# The cost factor (rounds) can be adjusted; 12 is a common default.
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds=12))
return hashed_password.decode('utf-8')
@staticmethod
def check_password(plaintext_password: str, hashed_password: str) -> bool:
"""Checks if a plaintext password matches a stored bcrypt hash."""
try:
return bcrypt.checkpw(plaintext_password.encode('utf-8'), hashed_password.encode('utf-8'))
except ValueError:
# Handle cases where the hashed_password might be malformed or not a bcrypt hash
return False
# Example Usage:
password = "MySecurePassword123!"
# Hash the password
secure_hash = PasswordManager.hash_password(password)
print(f"Original password: {password}")
print(f"Hashed password: {secure_hash}")
# Verify the password
is_correct = PasswordManager.check_password(password, secure_hash)
print(f"Is '{password}' correct? {is_correct}")
# Test with an incorrect password
incorrect_password = "WrongPassword"
is_incorrect = PasswordManager.check_password(incorrect_password, secure_hash)
print(f"Is '{incorrect_password}' correct? {is_incorrect}")
# Test with a malformed hash (should return False)
is_malformed = PasswordManager.check_password(password, "not-a-valid-hash")
print(f"Is '{password}' correct with malformed hash? {is_malformed}")