c MD5从openssl lib不匹配php MD5怎么来的


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

我正在尝试创建一个md5哈希,我正在与php md5哈希进行比较。

两者不一致

下面是我的c代码以及PHP比较

为什么两个md5不一样?

使命令

gcc -Wall -lssl  -o test test.c
代码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代码

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

php md5

05a671c66aefea124cc08b76ea6d30bb

c code md5

098f6bcd4621d373cade4e832627b4f6

sizeof(file_buffer)没有给出计算MD5和的正确长度。它只给你指针file_buffer的大小,根据你的平台可能是4或8。

在这种情况下,您可能最好像这样调用MD5()函数:

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