繁体   English   中英

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

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

所以我有一个数据库,其中一串散列密码存储在字符串中。 现在,我尝试将其下拉,然后将其与用户输入的纯文本密码进行比较。 这是一个例子:

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"

我不知道如何解决此错误,也无法在线找到更多有关此错误的信息。 任何帮助,将不胜感激。 谢谢

问题是您将密码强制转换为字符串。 使用解码和编码可确保密码以相同格式转换为字符串并返回。

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

我不是以任何方式编码格式的专家,因此这不一定在所有情况下都有效。 如果您的字节对象中包含无法使用utf8表示的字符,则可能会导致问题。 我将研究存储密码的最佳做法。 也许您甚至可以使用允许您直接存储python对象的pickle

暂无
暂无

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

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