Learn to use Python bcrypt module for hashing a plain text password into encrypted String. Also learn to match the supplied password with already stored encrypted password with bcrypt module.
1. Python bcrypt module
Bcrypt algorithm was designed by Niels Provos and David Mazières, based on the Blowfish cipher.
Bcrypt helps in preventing the brute-force search attacks by increasing the iteration count (rounds). The computation cost of the algorithm depends on parameterized
rounds, so it can be increased as computers get faster. It uses a salt to protect against rainbow table attacks, as well.
1.1. Installing bcrypt module
pip install command to install bcrypt module.
# Latest version pip install bcrypt # Any specific version pip install python-bcrypt==0.3.2
1.2. bcrypt Methods
|Returns a randomly-generated salt.|
|Hash a password. With randomly generated salt and optionally given number of rounds.|
|Check that a unhashed password matches the hashed password.|
2. Python bcrypt Examples
Example 1: Python bcrypt example to hash a password
import bcrypt passwd = b'user_password' # Hash a password for the first time hashed = bcrypt.hashpw(passwd, bcrypt.gensalt()) print ("Password hash is : " , hashed)
Password hash is : b'$2b$12$rt0asWjvT0IkAOfqlhKSau.f2UTMhMpGtlIYArco7MSKERkBhwioC'
Example 2: Python bcrypt example to match a password
import bcrypt passwd = b'user_password' # Hash a password for the first time hashed = bcrypt.hashpw(passwd, bcrypt.gensalt(10)) # Match with already stored hashed password matched = bcrypt.checkpw(passwd, hashed) print ("Password match is : " , matched)
Password match is : True
Happy Learning !!