crypto-algorithms icon indicating copy to clipboard operation
crypto-algorithms copied to clipboard

Sha256 calculates wrong hashes on 16 bit target

Open JoeMerten opened this issue 7 years ago • 3 comments

sha256("abc") should give:

ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f200‌​15ad

but calculates wrong

2bb53935edbba17dc04a04854518754d8a66484491b585b0d0700cd2512f5420

instead. See also https://stackoverflow.com/questions/22880627/sha256-implementation-in-c

It seems not to be an endianess issue. Any idea?

JoeMerten avatar Aug 28 '17 13:08 JoeMerten

We've also noticed this issue on a 16-bit platform so I was pleased to see this bug! It was low priority for us, but I finally got around to checking if there was an updated version here...

Digging a little into the code, it specifically says that you need to change the definition of "WORD" for 16-bit machines. https://github.com/B-Con/crypto-algorithms/blob/master/sha256.h#L20

Did you make that adjustment?

I've changed the code in md5.h, sha1.h and sha256.h (so they all match) on our system to:

#include <stdint.h>
typedef uint32_t  WORD;

I can't test it until tomorrow, but I expect that's the issue - I'll report back tomorrow.

karora avatar Aug 16 '18 17:08 karora

A long time after the fact making this comment, but I also needed an additional change in sha1.c and sha256.c as my compiler (NC308 Renesas) was not promoting the BYTEs to WORDs when performing the build of the WORDs from BYTES.

for (i = 0, j = 0; i < 16; ++i, j += 4) m[i] = ((WORD)data[j] << 24) | ((WORD)data[j + 1] << 16) | ((WORD)data[j + 2] << 8) | ((WORD)data[j + 3]);

WIthout this, the assembly code shows that the left shift operations were overflowing so was only the low byte (3).

youca04 avatar Jul 28 '21 06:07 youca04