flask-bcrypt - ValueError: Invalid salt

后端 未结 11 1502
北海茫月
北海茫月 2020-12-29 07:57

I was finishing up a simple user login with Flask and flask-Bcrypt. However, when trying to login with a user that is stored in my database, I keep getting this error

<
11条回答
  •  清酒与你
    2020-12-29 08:51

    In my case, the problem was related to a type conversion going on during password storage. Using bcrypt.generate_password_hash(plaintext) returns a binary value, like b'$2b$12$zf/TxXZ4JJZ/lFX/BWALaeo0M.wNXrQXLqIFjmZ0WebqfVo9NES56'.

    Like mine was, your password column is set up as a string:

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

    I found that generating the hash above, storing that binary value it in my string password column, then simply retrieving it resulted in a different value due to SQLAlchemy's type conversion - nothing to do with bcrypt at all!

    A question on correct column type helped me realise that for correct roundtrip I had to store passwords as binary. Try replacing your column definition with:

    password = db.Column(db.Binary(60), nullable=False)
    

    I don't know for certain but suggest that different production environments and databases might handle this type conversion differently (reversibly in some cases, not in others), perhaps explaining the mixed success @Samuel Jaeschke has had.

    This also explains why encoding the input string to a constrained character set (an earlier solution) might help in some cases and not others - if it causes the to/from type conversion to work then you'll recover the correct hash from the database for comparison.

    At any rate, that solved this problem for me.

提交回复
热议问题