Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

comparing hash digests with memcmp in C++

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading