3

I have a server computing the hash of an image and sending the image and hash to the client. I have the client computing the hash of the image it receives. This is the basic setup:

SERVER

unsigned char sum[MD5_DIGEST_LENGTH];
md5sum(tdata, sum);
w = write(newsockfd,sum,MD5_DIGEST_LENGTH);

CLIENT

unsigned char ssum[MD5_DIGEST_LENGTH];
w = read(sockfd,ssum,MD5_DIGEST_LENGTH);
unsigned char sum[MD5_DIGEST_LENGTH];
md5sum(imgpath, sum);
int j;
for (j = 0; j < MD5_DIGEST_LENGTH; j++)
    printf("%02x", ssum[j]);
printf("\n");
printf("CLIENT CHECKSUM: ", sum);
    for (j = 0; j < MD5_DIGEST_LENGTH; j++)
        printf("%02x", sum[j]);
printf("\n");

The outputs are the exact same, but how do I check their equality with an if statement? If I do:

if (sum == ssum)

it always evaluates as false.

Clinton Jooooones
  • 887
  • 3
  • 12
  • 19
  • 3
    One byte at a time. Arrays cannot be compared through `==`, as it only compares the addresses of their first element (which is, as you see, different -- and they should be). – Jongware May 10 '15 at 00:09
  • 1
    possible duplicate of [C String -- Using Equality Operator == for comparing two strings for equality](http://stackoverflow.com/questions/3933614/c-string-using-equality-operator-for-comparing-two-strings-for-equality) – harmic May 10 '15 at 00:14

2 Answers2

13

Use memcmp:

The memcmp() function shall compare the first n bytes (each interpreted as unsigned char) of the object pointed to by s1 to the first n bytes of the object pointed to by s2.

The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the objects being compared.

Shea Levy
  • 5,237
  • 3
  • 31
  • 42
6

sum and ssum are arrays, that means that they're pointers to a block of memory, so when you write if (sum == ssum), you're comparing two pointers. That's why, obviously, your output is always false, because the pointer to different blocks of memory can't be the same.

So, you need to compare two arrays by its elements. You can use memcmp:

bool isEqual = (memcmp(sum, ssum, MAX_DIGEST_LENGTH) == 0);
Chan Kha Vu
  • 9,834
  • 6
  • 32
  • 64
  • 1
    memcmp is *exactly* for this use case, why reinvent the wheel with a custom loop? – Shea Levy May 10 '15 at 01:22
  • @SheaLevy Yea, and also memcmp works **faster** than that loop. – Chan Kha Vu May 10 '15 at 08:48
  • 1
    The return value of memcmp is not a boolean. If it returns 1 or -1 that means the first byte did not match is less than or greater than the other value, respectively. If they are equal it return 0. – davidgyoung Oct 30 '18 at 00:17