简体   繁体   中英

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.

Input test should result in a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 .

Instead I'm getting the output e58f4aa9a69bb1cc73084c1c87e991d3d3bb2f98 .

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 uint32_t . Now I want to convert them to uint8_t 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 e58f4aa9a69bb1cc73084c1c87e991d3d3bb2f98 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM