Can hashes be different for the same bytes?

Asked

Viewed 139 times

5

I’ve found a flaw or I can’t deal with hashes. I have two bytes arrays random, one generated by an algorithm and one original. I am trying to make the algorithm EXACTLY the same as the original. Visually I managed, with the same bytes, the same size in the same positions.

But when checking the hashes using SHA-256, gives difference between the hashes to the byte arrays identical.

resultado

A is the hash of the original byte-array

is the hash of the generated byte-array

Ax are the bytes contained in the original byte-array

Ay are the bytes contained in the byte-array generated by the algorithm

Note that, Ax and Ay are practically identical. But their hashes are different. What is happening?

Method used to calculate hashes:

public static string ToHex(byte[] bytes, bool upperCase) {

    using (var k = new HMACSHA256()) {
        bytes = k.ComputeHash(bytes);
    }

    StringBuilder result = new StringBuilder(bytes.Length * 2);

    for (int i = 0; i < bytes.Length; i++)
        result.Append(bytes[i].ToString(upperCase ? "X2" : "x2"));

    return result.ToString();
}

I am currently using the . NET Standard 2.0.

  • Obs: This also happens with other hashes like MD5.

2 answers

6


To manufacturer’s documentation that you used to say that the secret key needed to calculate the hash is generated randomly. And at each run a new object is created. Then at different executions the result will be different. It is the same problem that people commit with Random, only that the opposite, they always generate the same seed, in this case it is always generating a different one because the object changes.

If you always want the same result you should do all calculations with the same object (which may not be possible in some scenarios, including different executions) or use a builder with a fixed key.

Never use a class without reading all of its documentation. In some cases it is good to read up on other types of namespace whole.

  • I didn’t know that hashs had a random key. This is new.

  • 1

    @Cypherpotato this type has yes, after all it requires you to always have a key to generate it, if you do not provide one, the class generates one for you randomly.

5

What happens is because you are using HMAC. The HMAC is a MAC, not a HASH itself, it is also called "Keyed Hash". Some recent hash algorithms, such as Blake2, have the Keyed Hash feature inside it (can be used for both a MAC and a KDF).

Every MAC needs a key, without it there is no guarantee of integrity and confidentiality. As told by @Maniero the function used generates a key for HMAC, if it is not set.

You can directly use the SHA256, the hash function itself, with the SHA256

Browser other questions tagged

You are not signed in. Login or sign up in order to post.