Search code examples
c++sha1

Binary values don't add up correctly


I'm trying to write an implementation of SHA-1 in C++. But for some reason I can't get it to work. Two values won't add up correctly.

I'm using this link to check the steps of SHA-1 with input test

In the first round of the function (for word 0) I have this sample of my code:

#define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c))))

a = 0xefcdab89;
b = 0x98badcfe;
c = 0x10325476;
d = 0xc3d2e1f0;

f = (b & c) | (d & (~b));

cout << LEFTROTATE(a, 5); // equal to 3903086636 (11101000101001000110000000101100)

cout << f; // equal to 2562383102 (10011000101110101101110011111110)

I want the two values to add up to give me LEFTROTATE(a, 5) + f, but I get the following:

cout << LEFTROTATE(a, 5) + f; // equal to 2170502442 (10000001010111110011110100101010)

I'm expecting the output to be 6465469738 (110000001010111110011110100101010) since 3903086636 + 2562383102 = 6465469738. The value decreases for some reason and I don't know why.


Solution

  • This is normal and expected. The addition used in SHA1 is defined as addition modulo 232, which occurs naturally when adding 32bit bitvectors. There is no 33rd bit so it cannot be set.

    The linked page shows some extra bits, but that's essentially just for show. They don't affect the result, they get explicitly truncated away on that page before those extra bits get any chance to affect anything.

    In practice those bits wouldn't exist in the first place because truncation is implicit.