You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用bcrypt加密存储的哈希密码如何与用户输入明文密码比对

bcrypt密码哈希一致性比对方案及代码修正

bcrypt每次生成的哈希字符串不同是因为其内置了随机盐机制,生成哈希时会自动生成随机盐混入运算,且最终的哈希值本身就包含了盐信息。比对时不需要自己额外处理盐,直接调用官方提供的校验方法即可。

你当前代码里的错误主要有两个:

  • 校验前多余调用gensalt()重新生成了新的随机盐,用新盐对用户输入的密码做哈希得到的结果,和数据库中用旧盐生成的哈希必然不匹配
  • checkpw的参数顺序传反了,正确的参数顺序是:第一个参数为用户输入的明文密码的字节格式,第二个参数为数据库存储的哈希值的字节格式

修正后代码

@login.route('/log',methods=['POST'])
def login():
    error = None
    # 从JSON获取请求数据
    body = request.get_json()

    if body is not None:
        if request.method == 'POST':
            # 校验参数非空
            validation = all(x != "" for x in body.values())
            if validation:
                username_mod = body['username']
                password_input = body['password_hash'] # 此处为用户提交的明文密码
                userMatch = User.query.filter_by(username=username_mod).first()
                
                pswd_match = False
                if userMatch:
                    # 直接传入明文密码字节和存储的哈希值做校验即可
                    store_pwd_bytes = userMatch.password_hash.encode('utf-8') if isinstance(userMatch.password_hash, str) else userMatch.password_hash
                    pswd_match = checkpw(password_input.encode('utf-8'), store_pwd_bytes)

                if userMatch and pswd_match:
                    return msg_handler("user allowed", 200)
                else:
                    return msg_handler("user denied", 400)
            else:
                return msg_handler("missing value in 1 or more parameters", 400)
        else:
            return msg_handler("Must be POST method", 400)
    else:
        return msg_handler("no data", 400)

调试截图

调试截图

内容的提问来源于stack exchange,提问作者Carlos Espinoza Garcia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:30:01