I am trying to program SHA256 implementation from this website: http://bradconte.com/sha256_c in a MSP430 MCU board. I am using the open-source Energia IDE for programming.
This is the testcode:
unsigned char hash[32];
SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx,(unsigned char*)"abc",3);
sha256_final(&ctx,hash);
PrintHex(hash);
This converts to hex
void PrintHex(unsigned char * data)
{
char tmp[16];
for (int i=0; i<32; i++) {
sprintf(tmp, "%02x",data[i]);
Serial.print(tmp);
}
}
The problem is that the output is always a wrong hash code.
This is the output:
2bb53935edbba17dc04a04854518754d8a66484491b585b0d0700cd2512f5420
Is it the testcode or something else that I am doing wrong here?
I ran that code on my system (Mac OS X, x86 64-bit) and it gave me this:
551ce4769446b343295ea7f819ba1c5557545e29a4de545746b2b246a9831f22
I think we can safely assume the code is crap: I verified that ba7816b... is the correct hash using some online tools, and now we see that your platform and mine both produce different results. I noticed some comment in the code about endianness so I looked it up and your system is also little-endian, so that shouldn't be a problem. I'd advise you to look for a different implementation.
You should not assume the string encoding to be portable in C.
Try this code instead:
unsigned char message[] = {0x61, 0x62, 0x63};
unsigned char hash[32];
SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx,message,sizeof message);
sha256_final(&ctx,hash);
PrintHex(hash);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With