Generate MD5 Hash using C

OpenSSL library

  1. Add linking against the OpenSSL library:

If building project with CMake then use the find_package() command to locate the needed library:

find_package(OpenSSL REQUIRED)
target_link_libraries(myapp OpenSSL::SSL)
  1. Generate MD5 hash:
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>

#define DIGEST_LENGTH 16

int main()
{
    const char *text = "Hello";

    unsigned char bytes[DIGEST_LENGTH];

    EVP_MD_CTX* context = EVP_MD_CTX_new();
    EVP_DigestInit_ex(context, EVP_md5(), NULL);
    EVP_DigestUpdate(context, text, strlen(text));
    unsigned int digestLength = DIGEST_LENGTH;
    EVP_DigestFinal_ex(context, bytes, &digestLength);
    EVP_MD_CTX_free(context);

    char digest[DIGEST_LENGTH * 2 + 1];
    for (int i = 0; i < DIGEST_LENGTH; i++) {
        sprintf(&digest[i * 2], "%02x", bytes[i]);
    }

    printf("%s\n", digest);

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.