The library you are using, Crypto, uses a salt value in addition to the password to create the hashed password. This salt value is randomly generated each time the password is hashed, and is stored alongside the hashed password.
When you later want to verify a password, the library uses the salt value stored with the hashed password, along with the provided password, to generate a new hash and compare it to the stored hash.
For you to compare the input password with the hashed password, you should use the same salt that was used while creating the hash. One way to achieve this is to store the salt value along with the hashed password, and then use it while verifying the new password.
Here's a simple example:
from Crypto.Hash import SHA256 from Crypto.Random import get_random_bytes # create a new password password = b'password' # generate a new salt value salt = get_random_bytes(16) # hash the password with the salt hasher = SHA256.new() hasher.update(salt + password) hashed_password = hasher.digest() # store the salt along with the hashed password # ... # later, when a user wants to change their password password_to_check = b'password' # get the salt from the stored value # ... # hash the provided password hasher = SHA256.new() hasher.update(salt + password_to_check) hashed_password_to_check = hasher.digest() # compare the new hash with the stored hash if hashed_password_to_check == hashed_password: # password is correct print("password is correct") else: # password is incorrect print("password is incorrect")
You can also try to use libraries like bcrypt or scrypt instead of Crypto, which handle the salting and comparing for you.