Val
Val

Reputation: 1822

How to verify user password with HMACSHA512?

I'm trying to write a method to verify a user's password which has been generated using HMACSHA512. The method receives the password to verify along with the original password hash and salt which have been retrieved from the database.

Unfortunately, the ComputeHash() method creates a different hash than the one in the database, for the same password. What am I doing wrong?

private bool VerifyPasswordHash(string passwordToVerify, byte[] oldUserPasswordHash, byte[] existingPswSalt)
{
    bool isSame = false;

    using (HMACSHA512 hasher = new HMACSHA512(existingPswSalt))
    {
        // Generates a new hash which is different than the original
        byte[] pswHash = hasher.ComputeHash(Encoding.UTF8.GetBytes(passwordToVerify));

        isSame = pswHash.SequenceEqual(oldUserPasswordHash);
    }

    return isSame;
}

Here's the method which generated the original hash and the salt:

private (byte[] PswHash, byte[] PswSalt) CreatePasswordHashAndSalt(string password)
{
    byte[] pswSalt;
    byte[] pswHash;

    using (HMACSHA512 hmac = new HMACSHA512())
    {
        pswSalt = hmac.Key;
        pswHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
    }

    return (pswHash, pswSalt);
}

Upvotes: 1

Views: 55

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76414

The experiment you need to perform looks like this:

var results = yourObject.CreatePasswordHashAndSalt("somepassword");
bool isItWorking = yourObject.VerifyPasswordHash("somepassword", results.Item1, results.Item2);

and isItWorking should be true. If it is not true, then you found a bug in the tool you use. If it is working, then you will need to debug the way you get the password in the second case and whether it indeed matches the first as well as the hash and salt needs to be compared for consistency.

Debug your code carefully and find out which step deviates your values from those expected for the first time. Note that there could be white characters involved into typing in the password, which may cause variances you do not necessarily see. So I expect the experiment above to yield a true and if so, then you have made a mistake somewhere else.

Upvotes: 0

Related Questions