哈希算法MD5实现 c语言并给代码注释
时间: 2024-04-29 16:26:22 浏览: 128
好的,我知道了。以下是哈希算法MD5的C语言代码注释:
```C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
// 将输入字符串转换为二进制表示,并进行填充
// 对于较短的输入,填充到长度为 448 mod 512
// 然后在末尾添加一个长度为 64 位的二进制数,表示输入长度
uint8_t *md5(const char *message) {
// 消息填充,以及长度记录
size_t initial_len = strlen(message);
uint8_t *msg = calloc(initial_len + 64, 1);
memcpy(msg, message, initial_len);
msg[initial_len] = 128;
uint64_t bits_len = 8 * initial_len;
memcpy(msg + initial_len + 56, &bits_len, 8);
// 初始化 MD 缓冲区
uint32_t h0 = 0x67452301;
uint32_t h1 = 0xEFCDAB89;
uint32_t h2 = 0x98BADCFE;
uint32_t h3 = 0x10325476;
// 循环压缩每个 512 位的消息块
for (int i = 0; i < initial_len + 64; i += 64) {
uint32_t *w = (uint32_t *)(msg + i);
uint32_t a = h0;
uint32_t b = h1;
uint32_t c = h2;
uint32_t d = h3;
// 进行 64 次操作
for (int j = 0; j < 64; ++j) {
uint32_t f, g;
if (j < 16) {
f = (b & c) | ((~b) & d);
g = j;
} else if (j < 32) {
f = (d & b) | ((~d) & c);
g = (5 * j + 1) % 16;
} else if (j < 48) {
f = b ^ c ^ d;
g = (3 * j + 5) % 16;
} else {
f = c ^ (b | (~d));
g = (7 * j) % 16;
}
uint32_t temp = d;
d = c;
c = b;
b += LEFTROTATE((a + f + k[j] + w[g]), r[j]);
a = temp;
}
h0 += a;
h1 += b;
h2 += c;
h3 += d;
}
// 将缓冲区拼接为最终的哈希值
uint8_t *result = calloc(16, 1);
memcpy(result, &h0, 4);
memcpy(result + 4, &h1, 4);
memcpy(result + 8, &h2, 4);
memcpy(result + 12, &h3, 4);
free(msg);
return result;
}
int main() {
char *message = "hello world";
uint8_t *hash = md5(message);
for (int i = 0; i < 16; ++i) {
printf("%02x", hash[i]);
}
printf("\n");
free(hash);
return 0;
}
```
以上是哈希算法MD5的C语言实现代码,并进行了注释,希望能够帮助你。
阅读全文