简体   繁体   中英

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 ?

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.

The MD5 function is now deprecated, so if you want to avoid all those nasty warnings in your code...

Here's a simple example of how to use md5 with OpenSSL 3.0 and above with C++:

#include <openssl/evp.h>
#include <cstdio>

using namespace std;

string md5(const string& content)
{
  EVP_MD_CTX*   context = EVP_MD_CTX_new();
  const EVP_MD* md = EVP_md5();
  unsigned char md_value[EVP_MAX_MD_SIZE];
  unsigned int  md_len;
  string        output;

  EVP_DigestInit_ex2(context, md, NULL);
  EVP_DigestUpdate(context, content.c_str(), content.length());
  EVP_DigestFinal_ex(context, md_value, &md_len);
  EVP_MD_CTX_free(context);

  output.resize(md_len * 2);
  for (unsigned int i = 0 ; i < md_len ; ++i)
    std::sprintf(&output[i * 2], "%02x", md_value[i]);
  return output;
}

According to:https://www.openssl.org/docs/man3.0/man3/EVP_DigestInit_ex.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM