Open In App

Password Hashing with Bcrypt in Flask

In this article, we will use Password Hashing with Bcrypt in Flask using Python. Password hashing is the process of converting a plaintext password into a hashed or encrypted format that cannot be easily reverse-engineered to reveal the original password. Bcrypt is a popular hashing algorithm used to hash passwords. It is a password-hashing function that is based on the Blowfish cipher and is designed to be slow and computationally expensive, making it more difficult for attackers to guess or crack passwords.

Key Terminologies:



Stepwise Implement with Bcrypt in Flask

Step 1: Install Flask-Bcrypt

To use Bcrypt in Flask, we need to install the Flask-Bcrypt extension. We can install it using pip.



pip install flask-bcrypt

Step 2: Import Flask-Bcrypt

We need to import the Bcrypt module from Flask-Bcrypt in our Flask app.




from flask_bcrypt import Bcrypt

Step 3: Create a Bcrypt Object

We need to create a Bcrypt object and pass our Flask app as an argument.




bcrypt = Bcrypt(app)

Step 4: Hash a Password

We need to decode the hashed password using Python decode(‘utf-8’) as the generate_password_hash() function returns a bytes object. We can hash a password using the generate_password_hash() function of the Bcrypt object.




hashed_password = bcrypt.generate_password_hash
                ('password').decode('utf-8')

Step 5: Verify a Password

The check_password_hash() function returns True if the password matches the hashed password, otherwise, it returns False. We can verify a password using the check_password_hash() function of the Bcrypt object.




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:

When we run the Flask app, we will see the following output.

Output

Related Articles: 


Article Tags :