Cartman123 Cartman123 - 1 year ago 89
C++ Question

Wrong hash in C++ implementation of SHA-1

I'm trying to write an implementation of SHA-1 in C++. For some reason I'm getting a different output than I'm expecting.


should result in

Instead I'm getting the output

I have the following function

void sha1(const uint8_t *org_msg, size_t org_len, uint8_t *digest)

Which I call like

// msg = original input
// org_len = original length of input
// output = uint8_t output[20];
sha1((uint8_t *)msg.c_str(), org_len, output);

I have these five variables at the end of the compression function (which are correct as you can see here at the botom of the page)

h0 = 10101001010010101000111111100101
h1 = 11001100101100011001101110100110
h2 = 00011100010011000000100001110011
h3 = 11010011100100011110100110000111
h4 = 10011000001011111011101111010011

The variables are all of type
. Now I want to convert them to
which I have the following function for:

void to_bytes(uint32_t val, uint8_t *bytes) {
bytes[0] = (uint8_t)val;
bytes[1] = (uint8_t)(val >> 8);
bytes[2] = (uint8_t)(val >> 16);
bytes[3] = (uint8_t)(val >> 24);

And I call it like

to_bytes(h0, digest);
to_bytes(h1, digest + 4);
to_bytes(h2, digest + 8);
to_bytes(h3, digest + 12);
to_bytes(h4, digest + 16);

And then finally output it like so:

for (size_t i = 0; i < 20; i++) {
printf("%2.2x", output[i]);

Which results in

Answer Source

to_bytes produces reversed output. bytes[0] will get the last 8 bits of the input, while you want the first 8 bits.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download