I'm trying to create a certain modular code using OpenSSL's EVP API for MD5 by passing the EVP_MD
object within functions as shown below.
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
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(&mdctx);
EVP_DigestInit_ex(&mdctx, md, NULL);
EVP_DigestUpdate(&mdctx, input_text, strlen(input_text)+1);
EVP_DigestFinal_ex(&mdctx, hash, &hash_len);
EVP_MD_CTX_cleanup(&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;
}
The problem is that on executing the code every time, I obtain a different hash value for the same text.
Such as
585c64a0
554454a0
5f75a4a0, etc
MD5 is deterministic and such an issue should not exist. Any reason why such as error exists? Also, the passing of the EVP_MD
object within functions is important to me.
EDIT:
Replacing the final printf
with the following code
for(int i = 0; i < 16; ++i)
printf("%02x", res[i]);
I get the following output.
b4000000000000000100000000000000
However, this stays the same for all executions. But I'm guessing that this hash isn't right.