How to create a md5 hash of a string in C?

前端 未结 6 736
独厮守ぢ
独厮守ぢ 2020-12-07 19:06

I\'ve found some md5 code that consists of the following prototypes...

I\'ve been trying to find out where I have to put the string I want to hash, what functions I

6条回答
  •  醉梦人生
    2020-12-07 19:25

    All of the existing answers use the deprecated MD5Init(), MD5Update(), and MD5Final().

    Instead, use EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_DigestFinal_ex(), e.g.

    // example.c
    //
    // gcc example.c -lssl -lcrypto -o example
    
    #include 
    #include 
    #include 
    
    void bytes2md5(const char *data, int len, char *md5buf) {
      // Based on https://www.openssl.org/docs/manmaster/man3/EVP_DigestUpdate.html
      EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
      const EVP_MD *md = EVP_md5();
      unsigned char md_value[EVP_MAX_MD_SIZE];
      unsigned int md_len, i;
      EVP_DigestInit_ex(mdctx, md, NULL);
      EVP_DigestUpdate(mdctx, data, len);
      EVP_DigestFinal_ex(mdctx, md_value, &md_len);
      EVP_MD_CTX_free(mdctx);
      for (i = 0; i < md_len; i++) {
        snprintf(&(md5buf[i * 2]), 16 * 2, "%02x", md_value[i]);
      }
    }
    
    int main(void) {
      const char *hello = "hello";
      char md5[33]; // 32 characters + null terminator
      bytes2md5(hello, strlen(hello), md5);
      printf("%s\n", md5);
    }
    

提交回复
热议问题