6

我正在尝试使用来自http://www.arp.harvard.edu的原始/未触及 md5.h 和md5c.c为字符串“Hello World”生成 MD5 哈希。但我的结果与我测试过的所有 md5 在线工具不同。这段代码有什么问题?谢谢你。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "md5.h"

void MD5hash(unsigned char *data, unsigned int dataLen, unsigned char *digest) {
    MD5_CTX c;
    MD5Init(&c);
    MD5Update(&c, data, dataLen);
    MD5Final(digest, &c);
}

int main(int argc, const char * argv[]) {
    unsigned char digest[16];
    const char *s = "Hello World";
    unsigned int l = (unsigned int)strlen(s);

    MD5hash((unsigned char *)s, l, digest);
    for(int i = 0; i < 16; ++i)
         printf("%02x", digest[i]);
    return 0;
}

// My result: f2877a72c40494318c4b050bb436c582
// But online tools output: b10a8db164e0754105b7a99be72e3fe5
4

2 回答 2

5

As @vipw mentioned there is an issue with padding. This MD5 implementation does not correctly manage padding for message sizes that are not a multiple of a MD5 block size (512-bit / 64 bytes).

To fix it on your side, replace:

const char *s = "Hello World";

by

const char s[64] = "Hello World";

EDIT:

There was a second issue related to portability in this MD5 implementation. In md5.h there is this type alias:

typedef unsigned long int UINT4;

On a Linux x86_64 system (which you are using), this must be changed to this:

typedef unsigned int UINT4;
于 2013-04-08T09:43:37.000 回答
1

您有填充问题。MD5 哈希算法适用于 512 位块。当您的最终块小于 512 位时,需要对其进行填充。在您的示例中,第一个块也是最后一个块,因为它小于 512 位。

填充格式称为Merkle-Damgård 构造

您可以在此处找到一些包含填充的伪代码。

于 2013-04-08T09:36:19.727 回答