Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm trying to compare a saved hash and a user input in python using bcrypt. My code:

while passnotcorrect == True:
            password = input("Enter password: ")
            password = password.encode('utf-8')
            file = open('password.txt', 'r')
            checkhash = file.read()
            file.close()
            checkhash = checkhash.encode('utf-8')
            if bcrypt.checkpw(password, checkhash):
                passnotcorrect = False
                os.system('cls||clear')
            else:
                print("Password is incorrect \n")

The error:

ValueError: Invalid salt

I'd really like some help with this. I'm not sure why this function would require the salt in the first place. Thanks

A little late but I think your issue is that you're trying to compare 'password' which is utf8 encoded string input with 'checkhash', another string read from a file.

Bcrypt.checkpw() takes in a UTF8 encoded string for the password to check as the first argument followed by the UTF8 encoded hash to compare the password being provided against to see if the provided pass matches the hash pass.

TLDR; you're passing two strings to the checkpw method, when the second argument needs to be the hash you're comparing against (gold standard).

db_pass = "pw-string123"  # from database
password = "pw-string123"  # from input
db_hashed_pass = bcrypt.hashpw(db_pass.encode('utf8'), bcrypt.gensalt())
print(f'Hashed pass to save in db: {db_hashed_pass}')
is_pass_matching = bcrypt.checkpw(password.encode('utf8'), db_hashed_pass)
print(f'Do passwords match? {is_pass_matching}')

Make sure your hashed password isn't being truncated (length matches) upon entry or retrieval.

I just gave up and used hashlib lol. Thanks for the answer, looks like that was my issue. Thanks – Thomas Nov 28, 2022 at 11:44

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.