Here is a diagram representing our counter mode hash function.
The counter is encrypted using the key,
which is then XORed with the message to produce the first cipher block.
And this is repeated for the second cipher block, et cetera.
Then each cipher block is XORed together to produce our hash value.
One way of creating a collision is to swap 2 of the cipher blocks.
For example, the first 2.
We can write this new hash as hash prime,
and it should be obvious that hash = hash prime.
Now let's look back at our diagram,
and for notation, let's refer to the value
coming out of the encryption as E0 and E1.
Then we have M0 XORed with E0 = C0
and M1 XORed with E1 = C1.
And we want to find M0 prime and M1 prime
such that when XORed with E0 you get C1,
and when XORed with E1, you get C0.
We can calculate M0 prime by first calculating E0 by reversing out the XOR
and then XORing E0 with C1 to get what we want.
So, in the code, here is a swap blocks routine
that calculates the 2 message blocks needed by first calculating
the eblock by reversing out the XOR
and then applying the XOR on the eblock with this swapped cipher block
and then returning both of them.
Here we get the inputs used for the cipher, which we then calculate.
These next lines grab the 4 blocks we need,
and then we calculate the new message blocks,
which then get replaced into the message, which is returned.
And then to test this, we call test, and it worked.
