Question
I'm trying to implement MD5 encoding functionality in a Tizen Native application. I've written the following code using OpenSSL's MD5 functions:
#include <openssl/md5.h>
char lsBuff[] = "abc";
unsigned char lucpMD5[100];
unsigned long lulLen = strlen(lsBuff);
MD5_CTX lmdContext;
MD5_Init(&lmdContext);
MD5_Update(&lmdContext, lsBuff, lulLen);
MD5_Final(lucpMD5, &lmdContext);
dlog_print(DLOG_INFO, "tag", "MD5 result: %s", lucpMD5);
However, when encoding "abc", I get this output:
MD5 result: РPШ<╥O░╓Ц?}(сr░Юл╕╕Ц│╕иuр┐√Dм╢алл╕
The correct MD5 hash for "abc" should be:
900150983cd24fb0d6963f7d28e17f72
How can I fix this issue to get the proper MD5 hash output?
Answer
Problem Understanding
The issue occurs because the MD5 hash is being printed directly as a string, while it's actually a binary digest. To display it correctly, you need to convert the binary hash to a hexadecimal string representation.
Solution Methods
-
Convert binary MD5 hash to hexadecimal string:
- The MD5 hash is 16 bytes long (128 bits)
- Each byte should be converted to two hexadecimal characters
- The final string should be 32 characters long
-
Use proper string formatting:
- Use
sprintfwith%02xformat specifier - Ensure proper buffer size for the hexadecimal string
- Use
Code Examples
Here's a complete working example:
char* get_md5_hash(const char* input) {
unsigned char digest[MD5_DIGEST_LENGTH];
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, input, strlen(input));
MD5_Final(digest, &context);
char* hash = malloc(33); // 32 characters + null terminator
for(int i = 0; i < 16; i++) {
sprintf(&hash[i*2], "%02x", (unsigned int)digest[i]);
}
hash[32] = '\0';
return hash;
}
// Usage example:
char* md5_hash = get_md5_hash("abc");
dlog_print(DLOG_INFO, "MD5", "Hash: %s", md5_hash);
free(md5_hash);
Additional Tips
- Remember to free the allocated memory after use
- For security purposes, consider using more secure hashing algorithms than MD5 when possible
- The hexadecimal output should always be 32 characters long for MD5
- Test with known values to verify your implementation (e.g., "abc" should produce "900150983cd24fb0d6963f7d28e17f72")