Can Hashes be different for the same bytes?

4

I found a flaw or I'm not sure how to deal with hashes . I have two random arrays , one generated by one algorithm and one original. I'm trying to make the algorithm look EXACTLY the same as the original. I visually managed, with the same bytes, the same size in the same positions.

  

Aisthehashoftheoriginalbyte-array

    

isthehashofthegeneratedbyte-array

    

Axarethebytescontainedintheoriginalbyte-array

    

Ayarethebytescontainedinthebyte-arraygeneratedbythealgorithm

Notethat,AxandAyarealmostidentical.Butyourhashesaredifferent.What'shappening?

Methodusedtocalculatehashes:

publicstaticstringToHex(byte[]bytes,boolupperCase){using(vark=newHMACSHA256()){bytes=k.ComputeHash(bytes);}StringBuilderresult=newStringBuilder(bytes.Length*2);for(inti=0;i<bytes.Length;i++)result.Append(bytes[i].ToString(upperCase?"X2" : "x2"));

    return result.ToString();
}

I'm currently using .NET Standard 2.0.

    
asked by anonymous 13.01.2018 / 05:27

2 answers

5

The builder documentation you used says the key secret to calculate the hash is generated randomly. And at each run a new object is created. Then in different runs the result will be different. It is the same problem that people commit with Random , only 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 must do all the calculations with the same object (which may not be possible in some scenarios, including different runs) or use a constructor with a fixed key .

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

    
13.01.2018 / 11:52
4

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

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

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

    
14.01.2018 / 16:22