title: OpenSSL MD5 gives a different hash every time
body: <p>I'm trying to create a certain modular code using OpenSSL's EVP API for MD5 by passing the <code>EVP_MD</code> object within functions as shown below.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;openssl/evp.h&gt;
  
  EVP_MD* md5_digest_init() {
    OpenSSL_add_all_digests();
    EVP_MD *md = EVP_get_digestbyname("MD5");
    if(!md) {
       printf("Unable to init MD5 digest\n");
       exit(1);
     }
    return md;
  }
  
  unsigned char *md5_digest_process(EVP_MD* md, unsigned char *input_text) {
      EVP_MD_CTX mdctx;
      unsigned char hash[EVP_MAX_MD_SIZE];
      int hash_len;
      EVP_MD_CTX_init(&amp;mdctx);
      EVP_DigestInit_ex(&amp;mdctx, md, NULL);
      EVP_DigestUpdate(&amp;mdctx, input_text, strlen(input_text)+1);
      EVP_DigestFinal_ex(&amp;mdctx, hash, &amp;hash_len);
      EVP_MD_CTX_cleanup(&amp;mdctx);
      return hash;
  }
  
  int main() {
    EVP_MD *md;
    md = md5_digest_init();
    unsigned char* res;
    res = md5_digest_process(md, "foobar");
    printf("%02x", res);
    return 0;
  }
  </code></pre>
  
  <p>The problem is that on executing the code every time, I obtain a different hash value for the same text.</p>
  
  <p>Such as</p>
  
  <pre><code>585c64a0
  554454a0
  5f75a4a0, etc
  </code></pre>
  
  <p>MD5 is deterministic and such an issue should not exist. Any reason why such as error exists? Also, the passing of the <code>EVP_MD</code> object within functions is important to me.</p>
  
  <p>EDIT:</p>
  
  <p>Replacing the final <code>printf</code> with the following code </p>
  
  <pre><code>for(int i = 0; i &lt; 16; ++i)
      printf("%02x", res[i]);
  </code></pre>
  
  <p>I get the following output.</p>
  
  <pre><code>b4000000000000000100000000000000
  </code></pre>
  
  <p>However, this stays the same for all executions. But I'm guessing that this hash isn't right.</p>