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
<Basically you would like to encode your data before the hash: password.encode('utf-8'). If it comes as unicode it may raise errors. Have a look here also: https://github.com/maxcountryman/flask-bcrypt/issues/9
My problem is similar to described by @tomClark
I use Postgres as my DDBB and his driver, or the DDBB system, encode always an already encoded string. The second encode process create an invalid hash like this:
'\\x24326224313224483352757749766438764134333757365142464f4f4f464959664d66673575467873754e466250716f3166375753696955556b2e36'
A correct hash looks like this:
$2b$12$Wh/sgyuhro5ofqy2.5znc.35AjHwTTZzabz.uUOya8ChDpdwvROnm
To resolve it, I decode the hash to utf8 first than save it to the DDBB.
Example code:
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
You need to apply .decode('utf-8')
to your self.password
:
def set_password(self, password):
"""Set password."""
self.password = bcrypt.generate_password_hash(password).decode('utf-8')
You completely don't need flask-bcrypt
for using bcrypt
.
Just do something like this:
class User(Base):
_password = db.Column("password", db.String, nullable=False)
@hybrid_property
def password(self):
return self._password
@password.setter
def password(self, value):
bvalue = bytes(value, 'utf-8')
temp_hash = bcrypt.hashpw(bvalue, bcrypt.gensalt())
self._password = temp_hash.decode('utf-8')
def check_password(self, value):
return bcrypt.checkpw(value.encode('utf-8'), self._password.encode('utf-8'))
I had the same problem. It turned out that the username and password combination I was trying to check was not hashed in the first place. Make sure that the password for the username you are trying to check is already hashed and not plain text. If the password is saved in plain text not hashed, you will get this error.
I had a similar problem. My code for checking the password was as follows:
if check_password_hash(form.password.data, user.pw_hashed):
When i reversed the order to:
if check_password_hash(user.pw_hashed, form.password.data):
It worked well.