Sha512 not returning equal in c# hash validation

The 64 bytes are the same, but the == is returning false. I am guessing there may be something wrong with the encoding, but I can not figure out what I am doing wrong. Any ideas to fix this?

public static byte[] hashSHA512(string unhashedValue)
{
    SHA512 shaM = new SHA512Managed();
    byte[] hash = shaM.ComputeHash(Encoding.UTF8.GetBytes(unhashedValue));
    return hash;

}

public static bool Validate(string enteredValue, byte[] hashedValue)
{
    byte[] hash = hashSHA512 (enteredValue);
    return (hash == hashedValue);
}

I tested this with a simple value and since they both call the same hash method I do not see how it can fail other than something in the encoding. I am just using the built in System.Security.Cryptography.

Jon Skeet
people
quotationmark

No, there's nothing wrong with the encoding - there is no encoding in a byte[]. They're just bytes. It's just a matter of == for arrays performing a reference comparison.

You could use SequenceEqual to compare the arrays:

public static bool Validate(string enteredValue, byte[] hashedValue)
{
    // TODO: Rename `hashSHA512 to follow .NET naming conventions
    byte[] hash = hashSHA512 (enteredValue);
    return hash.SequenceEqual(hashedValue);
}

Note that you'll need using System.Linq; in your using directives to bring in LINQ.

Alternatives:

  • Convert both to their base64 (text) representations and compare those
  • Write your own array equality checker, which could easily be more efficient than SequenceEqual

people

See more on this question at Stackoverflow