49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
"""bcrypt algorithm implementation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import binascii
|
|
|
|
import bcrypt as bcrypt_lib
|
|
|
|
|
|
class BcryptAlgorithm:
|
|
"""bcrypt password hashing algorithm."""
|
|
|
|
identifier = "bcrypt"
|
|
|
|
def hash(self, password: str, **kwargs) -> tuple[str, str]:
|
|
"""Hash a password using bcrypt.
|
|
|
|
Note: bcrypt generates its own salt internally and returns
|
|
a complete hash string that includes the salt.
|
|
We return empty string for salt_b64 and the full hash as hash_b64.
|
|
"""
|
|
hashed = bcrypt_lib.hashpw(password.encode("utf-8"), bcrypt_lib.gensalt())
|
|
# Return empty salt since bcrypt embeds salt in hash
|
|
return ("", base64.b64encode(hashed).decode("utf-8"))
|
|
|
|
def verify(
|
|
self,
|
|
password: str,
|
|
salt_b64: str,
|
|
hash_b64: str,
|
|
**kwargs,
|
|
) -> bool:
|
|
"""Verify a password against bcrypt hash.
|
|
|
|
Note: salt_b64 is ignored since bcrypt embeds salt in the hash.
|
|
"""
|
|
try:
|
|
hashed = base64.b64decode(hash_b64, validate=True)
|
|
return bcrypt_lib.checkpw(password.encode("utf-8"), hashed)
|
|
except (binascii.Error, ValueError):
|
|
return False
|
|
|
|
|
|
from algorithms import register_algorithm
|
|
|
|
# Auto-register when module is imported
|
|
register_algorithm(BcryptAlgorithm())
|