Password hashing with Crypto.HashPassword

redgreenwhite 20 Reputation points
2023-01-15T10:26:26.07+00:00

Hi.

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.

ASP.NET MVC
ASP.NET MVC
A Microsoft web application framework that implements the model-view-controller (MVC) design pattern.
598 questions
No comments
{count} votes

Accepted answer
  1. Dimple Rane 801 Reputation points
    2023-01-15T10:28:34+00:00

    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.

    No comments

1 additional answer

Sort by: Most helpful
  1. redgreenwhite 20 Reputation points
    2023-01-15T10:40:29.9133333+00:00

    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.

    Thanks.

    No comments