flask-bcrypt - ValueError: Invalid salt

我正在用Flask和flask-Bcrypt完成一个简单的用户登录。但是,当尝试使用存储在数据库中的用户登录时,我一直收到此错误

ValueError: Invalid salt

models.py

class User(db.Model):

__tablename__ = "users"

id = db.Column(db.Integer, primary_key=True)

name = db.Column(db.String, nullable=False)

email = db.Column(db.String, nullable=False)

password = db.Column(db.String, nullable=False)

posts = db.relationship("Post", backref="author", lazy="dynamic")

def __init__(self, name, email, password):

self.name = name

self.email = email

self.password = bcrypt.generate_password_hash(password)

def __repr__(self):

return '<User {}>'.format(self.name

views.py

@app.route("/login", methods=["GET", "POST"])

def login():

form = LoginForm()

if form.validate_on_submit():

user = User.query.filter(User.name == form.username.data).first()

if user and bcrypt.check_password_hash(user.password, form.password.data):

flash("you were just logged in!")

login_user(user)

return redirect(url_for("home"))

else:

flash("bad username or password")

return render_template("login.html", form=form)

表格

class LoginForm(Form):

username = StringField('username', validators=[DataRequired()])

password = PasswordField('password', validators=[DataRequired()])

回答:

我的问题类似于@tomClark所描述的

我将Postgres用作DDBB,而他的驱动程序或DDBB系统始终对已编码的string进行编码。第二个编码过程将创建一个无效的哈希,如下所示:

'\\x24326224313224483352757749766438764134333757365142464f4f4f464959664d66673575‌​467873754e466250716f3166375753696955556b2e36'

正确的哈希看起来像这样:

$2b$12$Wh/sgyuhro5ofqy2.5znc.35AjHwTTZzabz.uUOya8ChDpdwvROnm

为了解决这个问题,我先将哈希解码为utf8,然后再将其保存到DDBB。

示例代码:

def set_password(self, pw):

pwhash = bcrypt.hashpw(pw.encode('utf8'), bcrypt.gensalt())

self.password_hash = pwhash.decode('utf8') # decode the hash to prevent is encoded twice

以上是 flask-bcrypt - ValueError: Invalid salt 的全部内容, 来源链接: utcz.com/qa/431224.html

回到顶部