Password hashing converts plaintext passwords into secure hashed values that cannot be easily reversed. Bcrypt is a widely used password-hashing function based on the Blowfish cipher, designed to be computationally expensive and resistant to brute-force attacks, making password storage more secure in Flask applications.
Key Terminologies
- Password Hashing: The process of converting a plaintext password into a secure hashed format.
- Bcrypt: A password-hashing function based on the Blowfish cipher.
- Salt: Random data that is used as additional input to a one-way function that hashes a password or passphrase.
- Hashing Algorithm: A mathematical function that converts a plaintext password into a fixed-length hash value.
- Iterations: Iterations (Cost Factor): Determines how computationally expensive the bcrypt hashing process will be.
Implementation
Step 1: Install Flask-Bcrypt
Install the Flask-Bcrypt extension using pip to enable password hashing functionality.
pip install flask flask-bcrypt
Step 2: Import Flask-Bcrypt
Import the Bcrypt class from the flask_bcrypt module to use bcrypt hashing methods in the application.
from flask_bcrypt import Bcrypt
Step 3: Create a Bcrypt Object
Create a Bcrypt object by passing the Flask application instance to initialize bcrypt support for password hashing and verification.
bcrypt = Bcrypt(app)
Step 4: Hash a Password
Use the generate_password_hash() method to securely hash a plaintext password. The generated hash is decoded using decode('utf-8') because the method returns the hash as a bytes object.
hashed_password = bcrypt.generate_password_hash(
'password'
).decode('utf-8')
Step 5: Verify a Password
Use the check_password_hash() method to compare a plaintext password with its hashed version. The method returns True if both match; otherwise, it returns False.
is_valid = bcrypt.check_password_hash(
hashed_password,
'password'
)
Complete Code
Here is an example of how to implement Bcrypt in a Flask app.
from flask import Flask
from flask_bcrypt import Bcrypt
app = Flask(__name__)
bcrypt = Bcrypt(app)
@app.route('/')
def index():
password = 'password'
hashed_password = bcrypt.generate_password_hash
(password).decode('utf-8')
is_valid = bcrypt.check_password_hash
(hashed_password, password)
return f"Password: {password}<br>Hashed Password:
{hashed_password}<br>Is Valid: {is_valid}"
if __name__ == '__main__':
app.run()
Output:
After running the Flask application, the hashed password and verification result are displayed in the browser.
