Search code examples
copensslaesmd5

How can I use openssl/md5 in C++ to hash a string?


I need to hash with md5 algorithm a string in my program. There is the lib openssl but I'm a newbie about it. How is possible hash a string using that and where I can find a good doc that teach me how to use this lib, also with other function like aes?

I've tried this code:

int main()
{
    unsigned char result[MD5_DIGEST_LENGTH];
    const unsigned char* str;
    str = (unsigned char*)"hello";
    unsigned int long_size = 100;
    MD5(str,long_size,result);
}

But the compiler told me: undefined reference to MD5.

Why is there and undefined reference to MD5?


Solution

  • You should take a look at the documentation. An option is to use this function:

    #include <openssl/md5.h>
    unsigned char *MD5(const unsigned char *d, 
                       unsigned long n,
                       unsigned char *md);
    

    To which they state:

    MD2(), MD4(), and MD5() compute the MD2, MD4, and MD5 message digest of the n bytes at d and place it in md (which must have space for MD2_DIGEST_LENGTH == MD4_DIGEST_LENGTH == MD5_DIGEST_LENGTH == 16 bytes of output). If md is NULL, the digest is placed in a static array.

    As for AES, if you also want to use OpenSSL, then take a look at EVP doc and this example of how to use it. Just note that you have to add

    #define AES_BLOCK_SIZE 16
    

    In the top of the file for it to work, though.

    Btw. I can really recommend the Crypto++ library since it's great and has all kinds of cryptographic primitives; AES, Elliptic Curves, MAC, public-key crypto and so on.