Question

I am unable to get the md5 hash using OpenSSL. I am using the following command for build :

gcc -Wall test_3.c -o test_3 -lcrypto -lssl

but getting the the following link errors :

undefined reference to `MD5Init'
undefined reference to `MD5Update'
undefined reference to `MD5Final'
collect2: ld returned 1 exit status

The program is present below :

#include<stdio.h>
#include<string.h>
#include <openssl/hmac.h>
#include <openssl/md5.h>

int main()
{
  char    digest[17];
  char input[] = "asdfljiahfbqhebfjcnajclgfeliuaef";
  int length = strlen(input);

  MD5_CTX md5;

  MD5Init(&md5);
  MD5Update(&md5,input, length);
  MD5Final(digest,&md5);
  printf("digest  is %s \n",digest);

  return 0;
}

Please let me know if you know the problem.Please help me out

Was it helpful?

Solution

You made some mistakes, I've corrected them. Also I've added hexadecimal output of the hash. Otherwise it will break your terminal.

#include <stdio.h>
#include <string.h>
#include <openssl/hmac.h>
#include <openssl/md5.h>

int main()
{
    // use unsigned char
    unsigned char    digest[16];
    char *input = "hek2mgl";
    int length = strlen(input);
    int i=0;

    // don't miss the underscore after MD5
    MD5_CTX md5;    
    MD5_Init(&md5);

    while (length > 0) {
        if (length > 512) {
            MD5_Update(&md5, input, 512);
        } else {
            MD5_Update(&md5, input, length);
        }
        length -= 512;
        input += 512;
    }

    MD5_Final(digest, &md5);
    printf("digest is: ");
    for(i = 0; i < 16; i++) {
        printf("%02x", digest[i]);
    }
    printf("\n");
    return 0;
}

Output:

digest is: 1ff8a3b2958ee3340ed88a2b980a8099

OTHER TIPS

In addition to hek2mgl's answer, the OpenSSL wiki offers the following example at EVP Message Digests.

The EVP_* interfaces are recommended, especially for those who are not familiar with some of OpenSSL's features and quirks (which can be a good thing). Instead of EVP_sha256(), just use EVP_md5().

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

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

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

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

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

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

    EVP_MD_CTX_destroy(mdctx);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top