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

问题描述 投票:0回答:2

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

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"

我不知道如何解决这个错误,并且在网上找不到太多相关信息。任何帮助,将不胜感激。谢谢

python python-3.x hash passwords bcrypt
2个回答
0
投票

问题在于您将密码转换为字符串。使用解码和编码来确保密码被转换为字符串并使用相同的格式返回。

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 对象。


0
投票

我在 ipython (python 3.10) 中尝试过:

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'), bytes(hashed_password.replace("b'", "").replace("'", ""), 'utf-8')))
# -> False

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

这样就可以了。 输出是:

b'$2b$12$jYlhIXVWLMxBQDZ9QJH./e980gBUEy7PoDAMupnhcqQObVF7rQZW2'
False
True

© www.soinside.com 2019 - 2024. All rights reserved.