python - bcrypt.checkpw 返回 TypeError : Unicode-objects must be encoded before checking

标签 python bcrypt

我正在调用 bcrypt.checkpw 来检查未加密的密码是否与存储在凭证数据库中的散列密码相匹配,但收到了

TypeError: Unicode-objects must be encoded before checking

我该如何解决这个问题?有什么建议吗?
我安装了 python 2.7.6bcrypt 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

原因很简单:加密函数仅适用于字节字符串(实际上是数组)。

您的passwordhashed_pa​​ssword 必须都是字节串。

如果您使用bcrypt.hashpw() 函数,您的hashed_pa​​ssword 必须是一个字节串,我认为问题出在密码 值。此密码 必须来自类似的 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/

相关文章:

python - zipimport.ZipImportError : can't find module from program made with py2exe

python - 在 pandas 中连接 2 列 - AttributeError : 'DataFrame' object has no attribute 'concat'

python - 我正在使用 cv2.imread() 读取图像,并将其转换为灰度。但是为什么我显示的时候不是灰度的呢?

'Season Year' 等字符串的 Python 自定义排序函数

javascript - python bcrypt 和 node.js bcrypt

python - 如何使用 python 将流上传到 AWS s3

ruby-on-rails - Rails 设备 : Generating encrypted_password values (for test users)

php - 密码哈希、BCrypt 到 SHA1/MD5

python - 使用 php 格式的函数 password_hash() 的 Django 密码哈希器

grails - 将密码哈希从 SHA 转换为 bcrypt