Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same content, different MD5 - File and String

Tags:

c++

c

md5

  1. I have a file testfile and a string teststring.

  2. In a shell I wrote:
    echo "a" > testfile

  3. then xxd testfile
    so I can see the hexadecimal values of my filecontent
    output:

    0000000: 610a               a.
    
  4. see my code:

    int file;
    struct stat s;
    unsigned long size;
    char* buffer;
    char md5[MD5_DIGEST_LENGTH]
    
    file = open("testfile", O_RDONLY);
    if (file < 0)
        return false;
    
    if (fstat(file, &s) < 0)
    {
        close(file);
        return false;
    }
    
    size = s.st_size;                       //GET FILE SIZE
    printf("filesize: %lu\n", size);        //PRINT FILESIZE FOR DEBUGGING
    buffer = (char*)mmap(0, size, PROT_READ, MAP_SHARED, file, 0); //MAP FILE CONTENT TO BUFFER
    MD5((unsigned char*)buffer, size, md5); //GENERATE MD5
    munmap(buffer, size);                   //UNMAP BUFFER
    close(file);
    
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++)
        printf("%02x", md5[i]);
    printf("\n");
    
    
    unsigned char* teststring = "\x61\x0a"; //SAME STRING AS IN THE FILE
    
    MD5((unsigned char*)teststring, 2, md5);
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++)
        printf("%02x", md5[i]);
    printf("\n");
    
  5. it prints:

    filesize: 2  
    60b725f10c9c85c70d97880dfe8191b3  
    e29311f6f1bf1af907f9ef9f44b8328b  
    

    two completely different md5 hashes.
    i tried writing the buffer into a file
    and writing the teststring into a file they are the same!
    by why?
    isn't the buffer the same as the teststring?

like image 204
bricklore Avatar asked Apr 11 '13 08:04

bricklore


1 Answers

The correct hash is your first hash, 60b725f10c9c85c70d97880dfe8191b3.

$ echo "a" | md5
60b725f10c9c85c70d97880dfe8191b3

Your second hash happens to be the hash of "\x64\x0a", or the character 'd' followed by a newline:

$ echo "d" | md5
e29311f6f1bf1af907f9ef9f44b8328b

Are you sure the code you posted is what you are compiling/running? Did you forget to recompile? Are you executing an old binary?

like image 190
Mike Weller Avatar answered Nov 10 '22 10:11

Mike Weller