Python bcrypt Hash Code Example (Online Runner)
Python bcrypt hashing examples with configurable cost factor and verification, matching the online tool.
Online calculator: use the site bcrypt text tool.
Note: This snippet requires locally installed dependencies and will not run in the online runner.
Calculation method
bcrypt automatically generates a random salt for each hash. The tool exposes the cost factor (log rounds), which maps
straight to bcrypt.gensalt(rounds=cost).
Install the dependency first: pip install bcrypt.
Implementation notes
- Package:
bcryptis the standard Python binding for the bcrypt password hash. - Implementation:
gensalt(rounds=cost)embeds the cost and salt into the output string; verification only needs the stored hash. - Notes: bcrypt truncates passwords at 72 bytes, so normalize input encoding and length. Cost factors grow exponentially (each +1 doubles work), so tune for your latency budget.
python
import bcrypt
def bcrypt_hash(text: str, cost: int = 10) -> str:
salt = bcrypt.gensalt(rounds=cost)
return bcrypt.hashpw(text.encode("utf-8"), salt).decode("utf-8")
def bcrypt_verify(text: str, hashed: str) -> bool:
return bcrypt.checkpw(text.encode("utf-8"), hashed.encode("utf-8"))
# Example usage
hashed = bcrypt_hash("correct horse battery staple", cost=12)
print(hashed)
print(bcrypt_verify("correct horse battery staple", hashed))
Complete script (implementation + tests)
python
import bcrypt
def run_tests() -> None:
hashed = bcrypt.hashpw(b"password", bcrypt.gensalt(rounds=10))
assert bcrypt.checkpw(b"password", hashed), "bcrypt verify failed"
print("All bcrypt tests passed.")
if __name__ == "__main__":
run_tests()