38
votes

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?

5

5 Answers

64
votes

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
>>>
19
votes

The documentation doesn't mention storing the salt, it says you just have to:

#Initial generation
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
#Store hashed in your db

#Load hashed from the db and check the provided password
if bcrypt.hashpw(password, hashed) == hashed:
    print "It matches"
else:
    print "It does not match"

http://www.mindrot.org/projects/py-bcrypt/

6
votes

Later, let's say you have an user-input password user_pass. You'd hash that as well, and then compare the hash with the stored hash, and if they match, then the original passwords also matched.

Note that bcrypt automatically stores the salt value as part of the hashed password, so that you can use it when you hash the future input as well.

First time around:

import bcrypt

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

# store 'password_hashed' in a database of your choosing

Later times:

import bcrypt
password = something_that_gets_input()

stored_hash = something_that_gets_this_from_the_db()

if bcrypt.hashpw(password, stored_hash) == stored_hash:
    # password matches
4
votes

I'm not familiar with Python but I think you can use:
public static boolean checkpw(java.lang.String plaintext, java.lang.String hashed)

# Check that an unencrypted password matches one that has  
# previously been hashed.
if bcrypt.checkpw(plaintext, hashed):
    print "It matches"
else:
    print "It does not match"
0
votes

I think this one will work better:

for i in range(len(rserver.keys())):
    salt = bcrypt.gensalt(12)
    
    mdp_hash = rserver.get(rserver.keys()[i])
    rserver.set(rserver.keys()[i], bcrypt.hashpw(mdp_hash.encode(),bcrypt.gensalt(12) ))

    rsalt.set(rserver.keys()[i], salt)