bcrypt.checkpw返回类型错误:检查之前必须对Unicode对象进行编码

2024-03-29 08:18:39 发布

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

我正在调用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")

Tags: 密码objectsdefunicodepasswordberaiseencoded
3条回答

你可以这样做

bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))

很简单

我假设您使用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

原因很简单:加密函数只对字节字符串(或者实际上是数组)起作用。

密码和哈希密码必须都是字节字符串。

如果您使用bcrypt.hashpw()函数,那么您的散列密码必须是字节字符串,我认为问题在于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上的简单用法

我用那种东西

class User(Base):
    __tablename__ = "user"
    id = Column(BigInteger, primary_key=True, autoincrement=True)

    login = Column(String, nullable=False, unique=True)
    password = Column(String, nullable=False)

    @staticmethod
    def make_password_hash(password):
        hash = bcrypt.hashpw(password=password.encode('utf-8'), salt=bcrypt.gensalt())
        return hash.decode('utf-8')

    def is_password_valid(self, password):
        return bcrypt.checkpw(password.encode('utf-8'), self.password.encode('utf-8'))

相关问题 更多 >