packetie
packetie

Reputation: 5069

compile md5 checksum in C but got compile error

Tried to follow the example in SO example, but when compiling the following, got error:

$ gcc te.c
te.c: In function ‘main’:
te.c:10:17: error: storage size of ‘context’ isn’t known

Here is the code:

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


int main(int argc, char *argv[]) {
    unsigned char digest[16];
    const char* string = "Hello World";
    struct MD5_CTX context;
    MD5Init(&context);
    MD5Update(&context, string, strlen(string));
    MD5Final(digest, &context);
    int i;
    for (i=0; i<16; i++) {
        printf("%02x", digest[i]);
    }
    printf("\n");
    return 0;
}

By the way, my PC is running ubuntu 12.04 desktop. My gcc version is 4.7.3 and here is the version of libssl-dev

dpkg -l libssl-dev
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version        Description
+++-==============-==============-============================================
ii  libssl-dev     1.0.1-4ubuntu5 SSL development libraries, header files and

Any ideas?

UPDATE1

Thanks to Sourav Ghosh who pointed out that in the above, the struct in struct MD5_CTX context should be removed. Turned out the function name should be changed too, for example MD5Init to MD5_Init

This is working code:

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


int main(int argc, char *argv[]) {
    unsigned char digest[16];
    const char* string = "Hello World";
    MD5_CTX context;
    MD5_Init(&context);
    MD5_Update(&context, string, strlen(string));
    MD5_Final(digest, &context);
    int i;
    for (i=0; i<16; i++) {
        printf("%02x", digest[i]);
    }
    printf("\n");
    return 0;
}

To compile it, one needs to use gcc te.c -lssl -lcrypto. Thanks to an SO answer for this too!

Upvotes: 1

Views: 2610

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

I think, (and as I can see) MD5_CTX is already a typedef to a struct. You don't need to write struct MD5_CTX context;.

Change it to MD5_CTX context; and it should work.

Upvotes: 3

Related Questions