MFB MFB - 11 months ago 87
Python Question

How to store and compare password in db using py-bcrypt?

I would like to use py-bcrypt to store passwords in a db. Storing is easy:

import bcrypt

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

#then store password_hashed in db


But how to read and compare later? This is where I'm stuck.

Answer Source

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
>>>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download