简体   繁体   English

C为不同的字符串openssl获取相等的哈希值

[英]C getting equal hash values for different strings openssl

i am pretty new to c. 我对c很新。 I am trying to compare two files with md5. 我想用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. 您应该在启用所有警告和调试信息的情况下进行编译,例如在Linux上使用gcc -Wall -g

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. 新手和专家C程序员通常应该改进他们的代码,直到没有给出警告。 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); 你可以return strdup(hashwert); and have the convention that the calling function (the caller) should free the result. 并且具有调用函数(调用者)应该free结果的约定。

Or you could have a different API, for example having hashwert be a parameter of your function. 或者您可以使用不同的API,例如将hashwert作为函数的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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