Home > Back-end >  How Calculate MD5 and other hashes in C ?
How Calculate MD5 and other hashes in C ?

Time:08-04

I am trying to hash strings in C . I am trying to use the following code that I found to do a MD5 hash:

void digest_message(const unsigned char *message, size_t message_len, unsigned char **digest, unsigned int *digest_len)
{
    EVP_MD_CTX *mdctx;

    if((mdctx = EVP_MD_CTX_new()) == NULL)
        handleErrors();

    if(1 != EVP_DigestInit_ex(mdctx, EVP_md5(), NULL))
        handleErrors();

    if(1 != EVP_DigestUpdate(mdctx, message, message_len))
        handleErrors();

    if((*digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_md5()))) == NULL)
        handleErrors();

    if(1 != EVP_DigestFinal_ex(mdctx, *digest, digest_len))
        handleErrors();

    EVP_MD_CTX_free(mdctx);
}

This is the most promising thing I have found with this "openssl/evp.h" header file, but I don't understand how to use this function, how it works, and how to get my resulting hash in string format.

CodePudding user response:

For MD5 which is a 128-bit hash, you'd call it like this:

unsigned char* digest = nullptr;
unsigned int len = 0;

digest_message(message, message_len, &digest, &len);

Then to convert to 32-char hex string:

std::string s;
std::ostringstream ss;
for (unsigned int i = 0; i < len; i  )
{
    ss << std::hex << std::setfill('0') << std::setwidth(2) << digest[i];
}
s = ss.str();

Don't forget to free the allocated hash after converting it:

OPENSSL_free(digest);
  • Related