javahashshamessage-digest

Changing order of sha 256 update change the value


if i creat a messagedigist then update it with bytes values, change order change the ouput of the hash

Example

    BigInteger d_KGC = new BigInteger("773182302672421767750165305491852205951657281488");
    BigInteger r_KGC = new BigInteger("1354751385705862203270732046669540660812388894970");
    String C_ID = "id_c";

    hash_h_c.update(r_KGC.toByteArray());
    hash_h_c.update(d_KGC.toByteArray());
    hash_h_c.update(C_ID.getBytes());
    BigInteger h_c = new BigInteger(1, hash_h_c.digest());
    System.out.println(h_c);

output

49379655005878985488511725474312101658690290667242109419474456484341588492679

But if I change the order of updates like:

    hash_h_c.update(d_KGC.toByteArray());
    hash_h_c.update(r_KGC.toByteArray());
    hash_h_c.update(C_ID.getBytes());
    BigInteger h_c = new BigInteger(1, hash_h_c.digest());
    System.out.println(h_c);

output

74931638923759682675388497216517269416730536285702508607436092426996570518730

Isn't the overall result must be the same? or changing order result in diffrent hash


Solution

  • It's actually a good thing if changing the order of input changes the hash value. Otherwise you'd run into issues where "bat" and "tab" both hashed to the same value, for example. For cryptographic hashes like SHA-256, the goal is to make it impossible (with a very large but not infinite amount of resources) to find any other input that produces the same hash value, and "bat" and "tab" are two different inputs, so it would be both surprising and unfortunate if they had the same hash value.