How to compare plain text password to hashed password using bcrypt?

MFB picture MFB · Mar 4, 2012 · Viewed 36.5k times · Source

I would like to use bcrypt to hash passwords and later verify if a supplied password is correct.

Hashing passwords is easy:

import bcrypt

password = u'foobar'
password_hashed = bcrypt.hashpw(password, bcrypt.gensalt())

# then store password_hashed in a database

How can I compare a plain text password to the stored hash?

Answer

user1581840 picture user1581840 · Oct 21, 2012

With py-bcrypt, you don't need to store the salt separately: bcrypt stores the salt in the hash.

You can simply use the hash as a salt, and the salt is stored in the beginning of the hash.

>>> import bcrypt
>>> salt = bcrypt.gensalt()
>>> hashed = bcrypt.hashpw('secret', salt)
>>> hashed.find(salt)
0
>>> hashed == bcrypt.hashpw('secret', hashed)
True
>>>