简体   繁体   中英

How to compare hashed passwords stored as strings in python using bcrypt?

So I have a database where a bunch of hashed passwords are stored in strings. Now I am trying to then pull them down, and compare them to the plain text passwords the user enters. Here is an example:

import bcrypt

# at creation first:
password = u"seCr3t"
hashed_password = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
print(hashed_password)

#example of it being stored in the database
hashed_password = str(hashed_password)


# first attempt:
password = u"seCrEt"
print(bcrypt.checkpw(password.encode('utf8'), hashed_password.encode('utf8')))
# -> False

# second attempt:
password = u"seCr3t"
print(bcrypt.checkpw(password.encode('utf8'), hashed_password.encode('utf8')))
# -> True


# However I get the error "Invalid Salt"

I don't know how to get around this error and have not been able to find much about it online. Any help would be appreciated. Thanks

The problem is that you're casting the password to string. Use decode and encode to ensure the password gets converted to string and back using the same format.

import bcrypt

password = u"seCr3t"
hashed_password = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())

# convert to string with correct format
string_password = hashed_password.decode('utf8')

password = u"seCr3t"
# convert back to bytes with correct format
print(bcrypt.checkpw(password.encode('utf8'), string_password.encode('utf8')))
# True

I'm not an expert on encoding formats by any means, so this may not work in all cases. If you have a character in your bytes object that can't be represented using utf8, it could cause problems. I'd look into best practices for storing passwords. Maybe you could even use pickle which allows you to store python objects directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM