相同的内容,不同的MD5 - 文件和字符串

时间:2013-04-11 08:43:49

标签: c++ c md5

  1. 我有一个文件testfile和一个字符串teststring

  2. 在一个shell中我写道:
    echo "a" > testfile

  3. 然后xxd testfile
    所以我可以看到我的filecontent的十六进制值 输出:

    0000000: 610a               a.
    
  4. 查看我的代码:

    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. 打印:

    filesize: 2  
    60b725f10c9c85c70d97880dfe8191b3  
    e29311f6f1bf1af907f9ef9f44b8328b  
    

    两个完全不同的 md5哈希 我尝试将buffer写入文件中 并将teststring写入文件 ,它们是相同的
    为什么?
    bufferteststring相同吗?

1 个答案:

答案 0 :(得分:2)

正确的哈希值是您的第一个哈希值60b725f10c9c85c70d97880dfe8191b3

$ echo "a" | md5
60b725f10c9c85c70d97880dfe8191b3

您的第二个哈希恰好是“\ x64 \ x0a”的哈希值,或者字符“d”后跟换行符:

$ echo "d" | md5
e29311f6f1bf1af907f9ef9f44b8328b

您确定您发布的代码是您正在编译/运行的代码吗?你忘记重新编译了吗?你在执行旧的二进制文件吗?

相关问题