我正在调用 bcrypt.checkpw
来检查未加密的密码是否与存储在凭证数据库中的散列密码相匹配,但收到了
TypeError: Unicode-objects must be encoded before checking
我该如何解决这个问题?有什么建议吗?
我安装了 python 2.7.6
和 bcrypt 3.1.1
我有以下代码:
def check_password(password, hashed_password)
if not bcrypt.checkpw(password, hashed_password):
raise InvalidCredentials("403 Forbidden")
else:
return true
并收到以下错误:
File "/home/qt/virtualenv/lib/python2.7/site-packages/bcrypt/init.py", line 100, in checkpw
raise TypeError("Unicoed-objects must be encoded before checking")
TypeError: Unicode-objects must be encoded before checking
我查看了 bcrypt/__init__.py
,但不确定原因
def checkpw(password, hashed_password):
if (isinstance(password, six.text_type) or
isinstance(hashed_password, six.text_type)):
raise TypeError("Unicode-objects must be encoded before checking")
最佳答案
我假设您使用 Python 3。对于 Python 3,字符串默认为 unicode 字符串。
如果您使用 unicode 值调用 bcrypt.checkpw()
函数:
import bcrypt
password = "seCr3t" # unicode string
hashed_password = "hashed_seCr3t" # unicode string
bcrypt.checkpw(password, hashed_password)
你会得到这个异常
Traceback (most recent call last):
...
TypeError: Unicode-objects must be encoded before checking
原因很简单:加密函数仅适用于字节字符串(实际上是数组)。
您的password 和hashed_password 必须都是字节串。
如果您使用bcrypt.hashpw()
函数,您的hashed_password 必须是一个字节串,我认为问题出在密码 值。此密码 必须来自类似的 HTML 形式。要使用 bcrypt.checkpw()
函数,您必须首先使用与使用 bcrypt.hashpw( )
函数。通常,我们选择'utf8'编码。
例如(Python 2 和 3):
import bcrypt
# at creation first:
password = u"seCr3t"
hashed_password = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
# first attempt:
password = u"seCrEt"
bcrypt.checkpw(password.encode('utf8'), hashed_password)
# -> False
# second attempt:
password = u"seCr3t"
bcrypt.checkpw(password.encode('utf8'), hashed_password)
# -> True
请参阅 Gihub page 上的简单用法
关于python - bcrypt.checkpw 返回 TypeError : Unicode-objects must be encoded before checking,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40577867/