Password hashing with Crypto.HashPassword

redgreenwhite 20 Reputation points


For a school project, a new user's password was saved as Crypto.HashPassword. Now I'm trying to add option to change password, for that the user provides his current password and it compares to the saved, hashed one. The problem is, it keeps returning different hash for the same passwords. Does it use different salt every time? And if so how can I compare them?

Crypto.VerifyHashedPassword doesn't work.

A set of technologies in the .NET Framework for building web applications and XML web services.
3,186 questions
0 comments No comments
{count} votes

Accepted answer
  1. Dimple Rane 981 Reputation points

    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 =
    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 =
    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")
        # 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.

    2 people found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. redgreenwhite 20 Reputation points

    I appreciate your advice, but I was being an idiot and sending the wrong value to VerifyHashedPassword. After fixing it, I can confirm that VerifyHashedPassword does allow to compare saved and new password.


    0 comments No comments