i am pretty new to c. I am trying to compare two files with md5. I wrote a function which should return the hash values. But when comparing the values of different files or buffers, it says that they have the same hash.
unsigned char* getMD5(void *buffer, size_t bsize) {
EVP_MD_CTX *mdctx;
const EVP_MD *md;
unsigned char hashwert[EVP_MAX_MD_SIZE];
int hashwert_laenge;
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("MD5");
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, buffer, bsize);
EVP_DigestFinal_ex(mdctx, hashwert, &hashwert_laenge);
EVP_MD_CTX_destroy(mdctx);
return hashwert;
}
//in main...
char mess[] = "abc";
cahr mess2[] = "bcd";
if(strcmp(getMD5(mess, strlen(mess)),getMD5(mess2, strlen(mess2))==0) {
printf("euqal\n");
}else {
printf("not equal \n");
}
I always get that the buffers are equal, even if they are not. Regards
You should compile with all warnings enabled and debugging info, eg with gcc -Wall -g
on Linux.
It will have warned you: function returns address of local variable .
Newbies and expert C programmers usually should improve their code till no warnings are given. If your code triggers a warning that you really cannot avoid you should at least comment very carefully why.
You cannot meaningfully return the address of some local array.
You could return strdup(hashwert);
and have the convention that the calling function (the caller) should free
the result.
Or you could have a different API, for example having hashwert
be a parameter of your function.
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.