Reputation: 1349
So I am trying to create the MD5 hash of an arbitrary string in C using the openssl lib. This is what I go so far:
#include <stdio.h>
#include <string.h>
#include <openssl/md5.h>
void compute_md5(char *str, unsigned char digest[16]);
int main()
{
unsigned char digest[16];
compute_md5("hello world", digest);
printf("%s", digest);
return 0;
}
void compute_md5(char *str, unsigned char digest[16]) {
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, str, strlen(str));
MD5_Final(digest, &ctx);
}
However the output is full of unprintable characters. How can I properly display it as a hex string?
Upvotes: 3
Views: 4032
Reputation: 84561
You have it right, you just can't use printf("%s", digest);
to print digest
as a string. Note the unsigned char digest[16];
will be an array of unsigned char and will not be nul-terminated. You cannot print it as a string. Instead print each element as a hexadecimal number with 2 characters, e.g.
for (int i = 0; i < 16; i++)
printf("%02x", digest[i]);
putchar ('\n');
Your complete example would then be:
#include <stdio.h>
#include <string.h>
#include <openssl/md5.h>
void compute_md5(char *str, unsigned char digest[16]);
int main()
{
unsigned char digest[16];
compute_md5("hello world", digest);
for (int i = 0; i < 16; i++)
printf("%02x", digest[i]);
putchar ('\n');
return 0;
}
void compute_md5(char *str, unsigned char digest[16]) {
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, str, strlen(str));
MD5_Final(digest, &ctx);
}
Example Use/Output
$ ./bin/md5openssl
5eb63bbbe01eeed093cb22bb8f5acdc3
Creating A String From digest
If you need to create a string from digest
that you can print with printf ("%s\n", buf);
then you create a buffer and instead of writing the 2-char hex representation to stdout
, use sprintf
to write it to a buffer, nul-terminate the buffer and then print the string. You could do:
int main()
{
unsigned char digest[16];
char buf[sizeof digest * 2 + 1];
compute_md5("hello world", digest);
for (int i = 0, j = 0; i < 16; i++, j+=2)
sprintf(buf+j, "%02x", digest[i]);
buf[sizeof digest * 2] = 0;
printf ("%s\n", buf);
return 0;
}
(output is the same)
Let me know if that isn't what you are looking for.
Upvotes: 2