简体   繁体   English

来自openssl lib的c MD5与php md5不匹配怎么办?

[英]c MD5 from openssl lib does not match php md5 how come?

I am trying to create a md5 hash that I am comparing against a php md5 hash. 我正在尝试创建要与md5哈希进行比较的md5哈希。

The two don't seam to be the same 两者不相同

below is my c code along with the php compairison 以下是我的C代码以及php compairison

Why are the two md5 not the same? 为什么两个md5不同?

Make command 发出命令

gcc -Wall -lssl  -o test test.c

Code test.c 代码测试

#include <stdio.h>
#include <openssl/md5.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
#include <time.h>

unsigned char result[MD5_DIGEST_LENGTH];

// Print the MD5 sum as hex-digits.
void print_md5_sum(unsigned char* md, char* md5) {

    int i;

    for(i=0; i < MD5_DIGEST_LENGTH; i++) {

            char temp[3];
            snprintf(temp,sizeof(temp),"%02x",md[i]);

            if(i == 0){
                    strncpy(md5,temp,3);
            }else{
                    strncat(md5,temp,MD5_DIGEST_LENGTH);
            }
    }

        printf("md5 is %s \n", md5);
}

int main(int argc, char** argv ){

    char* file_buffer = "testtest";
    char buffer[MD5_DIGEST_LENGTH +1];

    MD5((unsigned char*) file_buffer, sizeof(file_buffer), result);

    printf("length %i\n", MD5_DIGEST_LENGTH);

        print_md5_sum(result,buffer);
        printf("%s \n" ,buffer);

        return 0;
}

php code PHP代码

<?php
    echo md5("testtest");
?>

results 结果

php md5 PHP的MD5

05a671c66aefea124cc08b76ea6d30bb

c code md5 C代码md5

098f6bcd4621d373cade4e832627b4f6

sizeof(file_buffer) does not give you the correct length to calculate the MD5 sum over. sizeof(file_buffer)没有给您正确的长度来计算MD5总和。 It only gives you the size of the pointer file_buffer, which will be likely either 4 or 8 depending on your platform. 它只会为您提供指针file_buffer的大小,根据您的平台,大小可能为4或8。

In this case you are probably better calling the MD5() function like this: 在这种情况下,您最好像这样调用MD5()函数:

MD5((unsigned char*) file_buffer, strlen(file_buffer), result);

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

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