在 postgres 中存储和检索哈希密码

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

我正在观看有关 FastAPI 的教程,在生成令牌之前,它将数据库从 SQLite 切换到 PostgreSQL。之前可以用,但现在出现错误,如下所示

return bcrypt.checkpw(password=password_byte_enc, hashed_password=hashed_password) TypeError: argument 'hashed_password': 'str' object cannot be converted to 'PyBytes'

我认为这是有关错误的代码:

def get_password_hash(password):
    # return bcrypt_context.hash(password)
    pwd_bytes = password.encode('utf-8')
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(password=pwd_bytes, salt=salt)
    return hashed_password


def verify_password(plain_password, hashed_password):
    password_byte_enc = plain_password.encode('utf-8')
    return bcrypt.checkpw(password=password_byte_enc, hashed_password=hashed_password)

完整的auth.py文件在这里https://pastebin.com/mHcd0YLU

我在这里输入用户名和密码来生成令牌,但出现错误:

python postgresql fastapi bcrypt
1个回答
0
投票

已解决 哈希后,需要使用decode属性将哈希密码正确存储在postgres数据库中

def get_password_hash(password):
    pwd_bytes = password.encode('utf-8')
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(password=pwd_bytes, salt=salt)
    string_password = hashed_password.decode('utf8')
    return string_password


def verify_password(plain_password, hashed_password):
    password_byte_enc = plain_password.encode('utf-8')
    hashed_password = hashed_password.encode('utf-8')
    return bcrypt.checkpw(password_byte_enc, hashed_password)

如果其他人有更好的解决方案,我愿意接受

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