如何使用bcrypt比较python中存储为字符串的散列密码?

2024-10-01 19:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个数据库,其中一堆散列密码存储在字符串中。现在我试着把它们拉下来,并与用户输入的纯文本密码进行比较。下面是一个例子:

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"

我不知道如何绕过这个错误,也没能在网上找到很多关于它的信息。任何帮助都将不胜感激。谢谢


Tags: the字符串用户数据库密码passwordutf8encode
1条回答
网友
1楼 · 发布于 2024-10-01 19:30:01

问题是您将密码强制转换为字符串。使用decode和encode确保密码转换为字符串并使用相同的格式返回。在

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

我不是编码格式方面的专家,所以这可能不适用于所有情况。如果你的bytes对象中有一个不能用utf8表示的字符,它可能会导致问题。我会研究存储密码的最佳实践。也许您甚至可以使用pickle,它允许您直接存储python对象。在

相关问题 更多 >

    热门问题