0

I have this code and I'm using python 3.7

def hash_password(password):
    return bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())


def credentials_valid(username, password):
    with session_scope() as s:
        user = s.query(User).filter(User.name.in_([username])).first()
        if user:
            return bcrypt.checkpw(password.encode('utf8'), user.password.encode('utf8'))
        else:
            return False

But when I try to run I get this error:

return bcrypt.checkpw(password.encode('utf8'), user.password.encode('utf8'))
AttributeError: 'bytes' object has no attribute 'encode'
3
  • 2
    what is the type of password variable? Commented Mar 18, 2020 at 8:20
  • I think the error say's AttributeError: 'bytes' object has no attribute 'encode' you can't encode byte to byte Commented Mar 18, 2020 at 8:39
  • Hi, im getting my password from a SQLite database. Commented Mar 18, 2020 at 18:44

1 Answer 1

2

checkpw(password, hashed_password) function of bcrypt takes encoded inputs.

Your two parameters, password and hashed_password, if they are in unicode, need to be encoded. This is what you did.
However, the "password" parameter that you gave to your function seems to be already encoded as the Python interpreter gave this AttributeError.

Check out this working implementation:

import bcrypt

password = "asd123"
hashed_password_encoded = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
hashed_password = hashed_password_encoded.decode("utf8")

is_valid = bcrypt.checkpw(password.encode('utf8'), hashed_password.encode('utf8'))
print(is_valid)
Sign up to request clarification or add additional context in comments.

2 Comments

Friend, im gettin my password from SQLite database.
@AndresHernandez If you are (and should) storing your password encrypted and in unicode instead of bytes, then you will need to do password.encode('utf8') to convert it to bytes. Whereas, if you are storing the password in bytes, then you do not need to encode it again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.