i’m trying to implement a login method for mongodb , using python (pymongo) and bcrypt. the problem comes when i try to compare hashes , they always are different :$ .
This is my test code( First of all i put into mongodb an user with a password hashed ):
using pythons scrypt :
bcrypt.hashpw('testpassword', bcrypt.gensalt(12))
'$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi'
db.users.insert({username: "yichuan",password: "$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi" });
Once we have put it into the db , i’m trying to make the magic :D:
def test_connectionManagerLoginPass(self):
connectionmanager=dbconnection.ConnectionManager()
username='yichuan'
password='testpassword'
hashed = bcrypt.hashpw(password, bcrypt.gensalt(12))
self.assertIsNotNone(connectionmanager.login(username,hashed), 'No error espected in login')
But the problem comes when i see hashed value:
'$2a$12$hw1DaWdOf3ECBcSgu2GB4Of3oAdKvyzl0xftBVzbyqkjK2A3X.LOm'
it is s totally different for wich one i have generated before!!! . Also i have been reading
that i didn’t need to save the bcrypt.gensalt(12) . So i’m a little confused.
Thanks for reading , Any help with what is wrong in my implementation of the auth?
posdata (more code):
def login(self,username,password):
if self.loginfieldsfilter(username,password):
dbdata = self.users.find_one({'username': username})
if password == dbdata[ 'password' ]:
return True
else:
return None
else:
return None
And yes , i’m sure that the db is giving me the correct fields.
For a password check you need to pass the hash itself as the salt, as it contains the salt as a prefix. This is a little confusing, but since you absolutely must use the same salt to get the same hash as before, that’s the only way:
(but I just put this together by copy&paste)