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

Flask使用flask-bcrypt校验密码时报ValueError: Invalid salt错误如何解决

问题根因与修复方案

核心报错原因

ValueError: Invalid salt 错误的直接诱因是密码哈希存储字段长度不足:bcrypt算法生成的UTF-8编码哈希值固定长度为60位,你当前User模型中password_hash字段设置为db.String(20),哈希值存入数据库时会被截断,导致完整盐值丢失,调用密码校验方法时读取到的是不完整的哈希值,因此抛出无效盐错误。

此外你的代码还存在一个隐藏bug:password属性的getter方法直接返回self.password会触发无限递归调用,最终导致栈溢出,需要一并修复。

修复步骤

  • 修改model.py中User模型的字段定义与属性方法:
class User(db.Model, UserMixin):
    name = db.Column(db.String(20), nullable=False)
    userName = db.Column(db.String(15), primary_key=True, nullable=False)
    # 将密码哈希字段长度调整为至少60位
    password_hash = db.Column(db.String(60), nullable=False)

    @property
    def password(self):
        # 修复递归问题:明文密码不可直接读取,抛出属性不可读错误即可
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, plain_text_password):
        self.password_hash = bcrypt.generate_password_hash(plain_text_password).decode('utf-8')
  • 执行数据库迁移,更新user表的password_hash字段长度。注意此前已经存入数据库的用户密码因为被截断已经失效,需要重新生成哈希后存入。
  • 重新测试登录功能即可解决报错。

内容的提问来源于stack exchange,提问作者Piyush Vikas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 12:45:07