c - 如何在 C 中创建字符串的 md5 散列?

标签 c md5

我发现了一些由以下原型(prototype)组成的 md5 代码......

我一直在努力找出我必须将要散列的字符串放在哪里,我需要调用哪些函数,以及散列后在哪里可以找到该字符串。我对结构中的 uint32 buf[4] 和 uint32 位[2] 感到困惑。

struct MD5Context {
    uint32 buf[4];
    uint32 bits[2];
    unsigned char in[64];
};

/*
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
 * initialization constants.
 */
void MD5Init(struct MD5Context *context);

/*
 * Update context to reflect the concatenation of another buffer full
 * of bytes.
 */
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len);

/*
 * Final wrapup - pad to 64-byte boundary with the bit pattern 
 * 1 0* (64-bit count of bits processed, MSB-first)
 */
void MD5Final(unsigned char digest[16], struct MD5Context *context);

/*
 * The core of the MD5 algorithm, this alters an existing MD5 hash to
 * reflect the addition of 16 longwords of new data.  MD5Update blocks
 * the data and converts bytes into longwords for this routine.
 */
void MD5Transform(uint32 buf[4], uint32 const in[16]);

最佳答案

我不知道这个特定的库,但我使用过非常相似的调用。所以这是我最好的猜测:

unsigned char digest[16];
const char* string = "Hello World";
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, string, strlen(string));
MD5Final(digest, &context);

这将为您返回散列的整数表示。如果您想将其作为字符串传递,则可以将其转换为十六进制表示形式。

char md5string[33];
for(int i = 0; i < 16; ++i)
    sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]);

关于c - 如何在 C 中创建字符串的 md5 散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627723/

相关文章:

powershell - 比较 Azure Properties.ContentMD5 和 Get-Filehash 之间的字符串输出

c - 如何在几秒钟内打印线程的生命周期?

c - 如何理解 "return *test== ‘\0’ ;"

c - Dev C 编译此代码,但在文件创建期间给出错误 3221225477

代码不起作用。但是调试的时候会出现这样的情况

php - 敏感数据的基本安全加密?

couchdb - CouchDB 附件的 md5 摘要格式是什么?

C# 等效于 PHP 的原始输出 MD5?

Python MD5 哈希计算更快

c - 如何检查从 C 传递的函数指针是否为非 NULL