Python bcrypt – Hash a Password with bcrypt

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

Use 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

Method Description
gensalt(rounds) Returns a randomly-generated salt.
Optional rounds parameter adjusts the work factor. Default value is 12.
hashpw(passwd, salt) Hash a password. With randomly generated salt and optionally given number of rounds.
checkpw(passwd, hashedPasswd) 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)

Program output.

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)

Program output.

Password match is :  True

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode