Home > Enterprise >  comparing hash digests with memcmp in C
comparing hash digests with memcmp in C

Time:01-09

I'm currently writing some tests for an MD5 hash generating function. The functions returns an unsigned char*. I have a reference sample to compare to hard coded into the test. From my research it appears that memcmp is the correct way to go, however I am having issues with the results.

When printed to the terminal they match, however memcmp is returning a negative match.

CODE sample:

 unsigned char ref_digest[] = "d41d8cd98f00b204e9800998ecf8427e";
 unsigned char *calculated_digest = md5_gen_ctx.get_digest();

std::cout << std::setfill('0') << std::setw(2) << std::hex << ref_digest << endl;

    for(int i = 0; i < MD5_DIGEST_LENGTH; i  ) {
        std::cout << std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(calculated_digest[i]);
    }
    cout << endl;
    int compare = std::memcmp(calculated_digest, ref_digest , MD5_DIGEST_LENGTH);
    cout << "Comparison result: " << compare << endl;

OUTPUT

2: Test timeout computed to be: 10000000
2: d41d8cd98f00b204e9800998ecf8427e
2: d41d8cd98f00b204e9800998ecf8427e
2: Comparison result: 70

Can anyone guide me as to what I am doing incorrectly here? I am wondering if there are issues with the definition of my reference hash. Is there a better way of managing this comparison for the test?

Cheers.

CodePudding user response:

This is wrong:

unsigned char ref_digest[] = "d41d8cd98f00b204e9800998ecf8427e";

That is a string of 32 characters, when what you want is an array of 16 bytes. Note that two hexadecimal characters (4 4 bits) corresponds to one byte.

To fix it, you can use a pair of 64-bit integers:

uint64_t ref_digest[] = {htobe64(0xd41d8cd98f00b204), htobe64(0xe9800998ecf8427e)};

I used htobe64() to put the bytes in the correct order, e.g. 0xd4 needs to be the first byte.

  •  Tags:  
  • c
  • Related