Python错误“bytes”对象没有属性“encode”

2024-04-25 13:23:14 发布

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

我有这段代码,我使用的是python 3.7

def hash_password(password):
    return bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())


def credentials_valid(username, password):
    with session_scope() as s:
        user = s.query(User).filter(User.name.in_([username])).first()
        if user:
            return bcrypt.checkpw(password.encode('utf8'), user.password.encode('utf8'))
        else:
            return False

但当我尝试运行时,会出现以下错误:

return bcrypt.checkpw(password.encode('utf8'), user.password.encode('utf8'))
AttributeError: 'bytes' object has no attribute 'encode'

Tags: 代码returndefusernamepasswordhashutf8encode
1条回答
网友
1楼 · 发布于 2024-04-25 13:23:14

checkpw(password, hashed_password)函数的bcrypt接受编码输入

您的两个参数password和hash_password(如果是unicode格式)需要进行编码。这就是你所做的。
但是,您为函数提供的“password”参数似乎已经编码为Python解释器提供的AttributeError

查看此工作实现:

import bcrypt

password = "asd123"
hashed_password_encoded = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
hashed_password = hashed_password_encoded.decode("utf8")

is_valid = bcrypt.checkpw(password.encode('utf8'), hashed_password.encode('utf8'))
print(is_valid)

相关问题 更多 >