Updated April 10, 2023
Introduction to Flask bcrypt
Flask bcrypt is defined as a flask extension that enables users with utilities related to bcrypt hashing.The bcrypt is a hashing function for password that is based on the Blowfish cipher and incorporates salt for protecting the application against any rainbow table attacks. We know, too many new terminologies. Let us decipher that! Salt is an additional input of random data that helps safeguard passwords when stored whereas rainbow table is a precomputed table that enables caching of cryptographic hash functions quite often used for cracking password hashes. The bcrypt is an adaptive function which can be deliberately made slower so that application is resistant to brute force attacks.
Syntax of Flask bcrypt
Here we will see some syntax of widely used commands in flask bcrypt. This is because when we go through working of bcrypt having a superficial understanding of syntax will enable easy grasping of the entire context.
1. Installing Flask bcrypt module in python.
pip install flask-bcrypt
2. Instantiate bcrypt object in python.
from flask import Flask
from flask.ext.bcrypt import Bcrypt
appBcrypt = Flask(__name__)
bcrypt = Bcrypt(appBcrypt)
3. Hash a password using defined method through the bcrypt object created.
Python 2:
hashVar = <bcrypt object>.generate_password_hash('< password to hash >')
Python 3:
hashVar = <bcrypt object>.generate_password_hash('< password to hash >') .decode('utf-8')
4. Check a hashed password through the bcrypt object created.
bcrypt.check_password_hash(hashVariable, '< password to hash >')
How bcrypt Works in Flask?
- In order to understand about hashing and in particular about bcrypt, it is important for us to understand a few terminologies which might be either new are so confusingly used that there is a need to clear the air of confusion. The first interchangeable terms that are used are Authentication and Authorization. In the process of authentication, we make sure on who the user is as they claim them to be, whereas in authorization, it is made sure that user is allowed to access a route or resource. Hence, the password about which we will talk about in hashing using Bcrypt, needs to undergo authentication and once authenticated, the user will be authorized to proceed with the next tasks.
- These passwords are very critical to oneself, as one’s either financial or personal data might be at risk of compromise in case the passwords falls into wrong hands and can even lead to a terrible security breach. Hence, the stored password should never be in plain text. Now, in case we need to store password, we need to hash a password and then store it into the database. This process of hashing is alternatively termed as one-way encryption which has a motto of never decrypting the password. Now, if the password is never decrypted, how does it authenticate. For this we hash the password sent by user and then match the hash value instead of performing decrypt on the stored hashed password. One of the technique or modules which enables flask to perform such hashing operation is present in flask bcrypt about which we will now know on how this module works, now that we have the clear understanding of the circumstances bcrypt works in.
- At first, we would need to install the flask-bcrypt module in the environment that is used for development of the flask application. We would need to use pip command while installing the module. As a next step, we would need to start building our flask application where we would need to first import the installed module. Once the import is complete, we would need to instantiate the object of bcrypt. With this we can now use the object created throughout the code. At this point we have an object of bcrypt created that will have all the API calls necessary for the utilities of hashing in a flask application.
- There are various hash methods present. With any one of the hashing methods, we would try to generate a password hash by available hashlib ones and keep the hashed password same. With this hashed password, when a user tries to input another password, we would use the API of check_password_hash. This API will take in 2 values, one being the hash value and the other being the input of the user. Now the API will try to hash the value of the input by user and then look if the hash value of the user input matches to the hash value of the stored password and in this way it will authenticate the user.
- Incase one tries to look at the hashed password, what they will see is a byte literal which might not make any sense, but instead contains information of the hashed value and also about the information on how the password was hashed. We also talked about a utility of bcrypt where in we can increase the time it takes to hash the password. By doing this we can delay the quick successive brute force attacks and thus saving from any malicious attacks. With this we now know the working of bcrypt in flask and what environment are they used in.
Examples of Flask bcrypt
Given below are the examples of Flask bcrypt:
Example #1
Installing flask bcrypt module in python.
Syntax:
pip install flask-bcrypt
Output:
Example #2
Hash a password using defined method through the bcrypt object created.
Syntax:
from flask import Flask, request
from datetime import timedelta
from flask_bcrypt import Bcrypt
appBcrypt = Flask(__name__)
bcryptObj = Bcrypt(appBcrypt)
@appBcrypt.route("/login", methods = ['POST','GET'])
def login():
if request.method == 'POST':
studentName = request.form['studentName']
password = request.form['password']
hashPassword = bcryptObj.generate_password_hash(password)
return '''<h1> The name of the Student is: {} <br>
The password is: {} <br>
The hashed password is being followed is: {}'''.format(studentName, password, hashPassword)
return '''<form method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "studentName" /></p>
<p>Enter Password:</p>
<p><input type = "text" name = "password" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>'''
if __name__ == "__main__":
appBcrypt.run(debug=True)
Output:
Example #3
Check a hashed password through the bcrypt object created.
Syntax:
from flask import Flask, request
from datetime import timedelta
from flask_bcrypt import Bcrypt
appBcrypt = Flask(__name__)
bcryptObj = Bcrypt(appBcrypt)
@appBcrypt.route("/login", methods = ['POST','GET'])
def login():
if request.method == 'POST':
studentName = request.form['studentName']
password = request.form['password']
hashPassword = bcryptObj.generate_password_hash(password)
if bcryptObj.check_password_hash(hashPassword, 'eduCBA'):
return '''<h1> The name of the Student is: {} <br>
The password matches with the first group'''.format(studentName)
elif bcryptObj.check_password_hash(hashPassword, 'eduCBAPremium'):
return '''<h1> The name of the Student is: {} <br>
The password matches with the Premium group'''.format(studentName)
else:
return ''' None of the group '''
return '''<form method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "studentName" /></p>
<p>Enter Password:</p>
<p><input type = "text" name = "password" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>'''
if __name__ == "__main__":
appBcrypt.run(debug=True)
Output:
Password matches the first group:
Password matches the premium group:
Password matches the none of the groups:
Conclusion
In this article we have got to know about the full details of what bcrypt is and an hands-on training on how hashing looks like and how hashed values are checked even without decrypting it back. Now it lies in hands of reader to utilize the knowledge in their flask application password hashing.
Recommended Articles
We hope that this EDUCBA information on “Flask bcrypt” was beneficial to you. You can view EDUCBA’s recommended articles for more information.