简体   繁体   中英

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.

The two don't seam to be the same

below is my c code along with the php compairison

Why are the two md5 not the same?

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
    echo md5("testtest");
?>

results

php md5

05a671c66aefea124cc08b76ea6d30bb

c code md5

098f6bcd4621d373cade4e832627b4f6

sizeof(file_buffer) does not give you the correct length to calculate the MD5 sum over. It only gives you the size of the pointer file_buffer, which will be likely either 4 or 8 depending on your platform.

In this case you are probably better calling the MD5() function like this:

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

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.

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