md5加密算法c语言实现
时间: 2024-01-19 15:17:59 浏览: 126
md5.zip_C语言加密算法_c语言 md5加密_md5 c语言_md5算法
以下是一个用C语言实现的MD5加密算法的示例:
```c
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
void md5(uint8_t *initial_msg, size_t initial_len) {
uint32_t h0, h1, h2, h3;
uint8_t *msg = NULL;
uint32_t *w = NULL;
uint32_t a, b, c, d, i, f, g, temp;
size_t new_len, offset;
// 初始化变量
h0 = 0x67452301;
h1 = 0xEFCDAB89;
h2 = 0x98BADCFE;
h3 = 0x10325476;
// 对消息进行预处理
new_len = ((((initial_len + 8) / 64) + 1) * 64);
msg = (uint8_t *)malloc(new_len);
memcpy(msg, initial_msg, initial_len);
msg[initial_len] = 128;
offset = initial_len + 1;
while (offset < new_len - 8) {
msg[offset] = 0;
offset++;
}
uint64_t bits_len = (uint64_t)initial_len * 8;
memcpy(msg + new_len - 8, &bits_len, 8);
// 处理消息的每个块
for (offset = 0; offset < new_len; offset += 64) {
w = (uint32_t *)(msg + offset);
// 初始化散列值
a = h0;
b = h1;
c = h2;
d = h3;
// 主循环
for (i = 0; i < 64; i++) {
if (i < 16) {
f = (b & c) | ((~b) & d);
g = i;
} else if (i < 32) {
f = (d & b) | ((~d) & c);
g = (5 * i + 1) % 16;
} else if (i < 48) {
f = b ^ c ^ d;
g = (3 * i + 5) % 16;
} else {
f = c ^ (b | (~d));
g = (7 * i) % 16;
}
temp = d;
d = c;
c = b;
b = b + LEFTROTATE((a + f + k[i] + w[g]), r[i]);
a = temp;
}
// 更新散列值
h0 += a;
h1 += b;
h2 += c;
h3 += d;
}
// 释放内存
free(msg);
// 输出散列值
printf("MD5 Hash: %08x%08x%08x%08x\n", h0, h1, h2, h3);
}
int main() {
char *msg = "Hello, world!";
size_t len = strlen(msg);
md5((uint8_t *)msg, len);
return 0;
}
```
阅读全文