3

I found a working example in which the correct MD5 sum of the text 'hoi' is printed. Now I'm trying to put it into a function but I can't get it to output the right MD5 sum.

The following code is what I made:

void md5_string (const char *input) {
    unsigned char digest[MD5_DIGEST_LENGTH];

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

    char mdString[33];

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

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

}

but it gives: 7165f036e29c8043961ab1eb606302f5 as output.

The correct output is given with the code below as well as in Bash with printf "hoi" | md5sum

unsigned char digest[MD5_DIGEST_LENGTH];
char string1[] = "hoi";

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

char mdString[33];

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

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

it gives: 4216455ceebbc3038bd0550c85b6a3bf

I am sure it has something to do with my pointer wisdom or trailing \0 characters but I can't get it right. Can anybody help me with this?

Niels
  • 537
  • 5
  • 22
  • The second example uses `char string1[] = "hoi";`, what does you call to `md5_string()` look like? – Mawg says reinstate Monica Mar 16 '18 at 10:36
  • Yes, so how do I convert a variable input to something like this? – Niels Mar 16 '18 at 10:39
  • 2
    You have too many &s: use `MD5((unsigned char*)input, strlen(input), (unsigned char*)digest);` and `MD5((unsigned char*)string1, strlen(string1), (unsigned char*)digest);`. `input`, `digest` and `string1` are _already_ pointers. – Jabberwocky Mar 16 '18 at 10:39
  • 3
    Remove both `&` operators from the line `MD5((unsigned char*)&string1, strlen(string1), (unsigned char*)&digest);`. For good measure remove the second cast (it's redundant) – M.M Mar 16 '18 at 10:39
  • Can anybody explain why the &s work in my lower (working) example and not when I put the in a function (upper, non-working) – Niels Mar 16 '18 at 10:45
  • 1
    Please add signature of function `MD5`, as well the code that shows how you call the function `md5_string`. As it stands, this code should not work correctly in lower example as well. – Marko Popovic Mar 16 '18 at 11:26
  • it's the MD5 function of openssl/md5.h – Niels Mar 16 '18 at 16:26
  • And another possible mistake is when you do strlen(string1). If string1 variable doesn.t have an end character, you cannot be sure of the length that md5 is computed on. You should pass in your md5_string function also the length, just to make sure that everything is fine. – Mihai Mar 20 '18 at 12:05

0 Answers0