Flask-Bcrypt
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. It uses the bcrypt password-hashing function, which is intentionally slow and resistant to brute-force attacks, making it suitable for securing sensitive data like passwords. The current version is 1.0.1, and it maintains an active development status with periodic updates.
Warnings
- breaking Enabling or disabling the `BCRYPT_HANDLE_LONG_PASSWORDS` configuration option on an existing project will break password checking for all users. This option changes how passwords longer than 72 bytes are handled.
- gotcha `generate_password_hash()` returns a byte string. In Python 3, this often needs to be explicitly decoded (e.g., using `.decode('utf-8')`) before storing in a database column that expects a Unicode string, or when passing it to `check_password_hash` if the stored hash is a string.
- gotcha Storing the hashed password in a database column with insufficient length (e.g., `VARCHAR(50)`) will truncate the hash, causing `check_password_hash` to consistently return `False` even for correct passwords.
- gotcha A `ModuleNotFoundError: No module named 'bcrypt'` error can occur if the underlying `bcrypt` library is not installed correctly or if Python development headers are missing on non-Windows systems during its installation.
- gotcha When using `flask-bcrypt` with databases like PostgreSQL, you might encounter encoding-related `TypeError` issues if hashed passwords or plaintext passwords are not consistently handled as byte strings during comparison.
Install
-
pip install flask-bcrypt
Imports
- Bcrypt
from flask_bcrypt import Bcrypt
Quickstart
from flask import Flask
from flask_bcrypt import Bcrypt
app = Flask(__name__)
# Configure secret key for session management, if applicable
app.config['SECRET_KEY'] = 'a_very_secret_key_for_demo'
bcrypt = Bcrypt(app)
# Example usage in a Flask context (e.g., a route or application setup)
password_plaintext = "mysecretpassword123"
# Generate a password hash (output is bytes, must decode for storage/comparison as string in Py3)
pw_hash = bcrypt.generate_password_hash(password_plaintext).decode('utf-8')
print(f"Plaintext Password: {password_plaintext}")
print(f"Hashed Password: {pw_hash}")
# Check a password against the hash
is_correct = bcrypt.check_password_hash(pw_hash, password_plaintext)
print(f"Password check against correct password: {is_correct}") # Should be True
is_wrong = bcrypt.check_password_hash(pw_hash, "wrongpassword")
print(f"Password check against wrong password: {is_wrong}") # Should be False
if __name__ == '__main__':
# In a real app, you would store pw_hash in a database
# and then retrieve it for check_password_hash
# For demonstration, we just print the results.
print("Quickstart demonstrated hashing and checking.")