简体   繁体   English

如何使用bcrypt比较在python中存储为字符串的哈希密码?

[英]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. 如果您的字节对象中包含无法使用utf8表示的字符,则可能会导致问题。 I'd look into best practices for storing passwords. 我将研究存储密码的最佳做法。 Maybe you could even use pickle which allows you to store python objects directly. 也许您甚至可以使用允许您直接存储python对象的pickle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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