user987654
user987654

Reputation: 79

Unexpected MD5 hash value using openssl/md5

When calculating the hash value of a hard coded string, i got a correct value.

unsigned char digest[MD5_DIGEST_LENGTH];
char string[] = "fnamelname";
MD5((unsigned char*)&string, strlen(string), (unsigned char*)&digest);
char mdString[33];

for(int i = 0; i < 16; i++)
   sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

printf("fullName: %s\n", string);
printf("md5 digest: %s\n", mdString);

When calculating the hash value of a prepared string, i got an incorrect/changed hash value.

char* fname = "fname";
char* lname = "lname";
char* fullname = new char[strlen(fname) + strlen(lname) + 1];
strcpy(fullname, fname);
strcat(fullname, lname);

MD5((unsigned char*) &fullname, strlen(fullname), (unsigned char*) &digest);

char mdString1[33];

for (int i = 0; i < 16; i++)
sprintf(&mdString1[i * 2], "%02x", (unsigned int) digest[i]);

printf("fullname: %s\n", fullname);
printf("md5 digest: %s\n", mdString1);

Upvotes: 1

Views: 2666

Answers (1)

interjay
interjay

Reputation: 110191

You are using a pointer to a pointer here, instead of a pointer to the data:

MD5((unsigned char*) &fullname, strlen(fullname), (unsigned char*) &digest);

It should be:

MD5((unsigned char*) fullname, strlen(fullname), (unsigned char*) &digest);

In your first example it happened to work because a pointer to an array points to the same place in memory as a pointer to its first element (depsite having different types). But even there it would be preferable to remove the &.

Upvotes: 2

Related Questions