C语言MD5算法程序
时间: 2023-07-26 10:15:04 浏览: 95
以下是一个简单的C语言实现MD5算法的程序:
```c
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define ROTLEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
void md5(uint8_t *initial_msg, size_t initial_len, uint8_t *digest) {
//定义常量
uint32_t h0, h1, h2, h3;
h0 = 0x67452301;
h1 = 0xEFCDAB89;
h2 = 0x98BADCFE;
h3 = 0x10325476;
//计算消息长度
uint8_t *msg = NULL;
size_t new_len, offset;
uint32_t w[16];
int i;
for (new_len = initial_len + 1; new_len % 64 != 56; new_len++);
msg = (uint8_t*)calloc(new_len + 8, 1);
memcpy(msg, initial_msg, initial_len);
msg[initial_len] = 0x80;
for (offset = initial_len + 1; offset < new_len; offset++);
uint64_t bits_len = 8 * initial_len;
memcpy(msg + offset, &bits_len, 8);
//主循环
for (offset = 0; offset < new_len; offset += (512 / 8)) {
//初始化 a, b, c, d
uint32_t a, b, c, d;
a = h0;
b = h1;
c = h2;
d = h3;
//将消息分块,每块512位
for (i = 0; i < 16; i++) {
w[i] = ((uint32_t)msg[offset + i * 4]) |
(((uint32_t)msg[offset + i * 4 + 1]) << 8) |
(((uint32_t)msg[offset + i * 4 + 2]) << 16) |
(((uint32_t)msg[offset + i * 4 + 3]) << 24);
}
//计算四轮循环
uint32_t f, g;
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;
}
uint32_t tmp = d;
d = c;
c = b;
b = b + ROTLEFT((a + f + w[g] + 0x5A827999), 5);
a = tmp;
}
//更新哈希值
h0 += a;
h1 += b;
h2 += c;
h3 += d;
}
//拼接哈希值
memcpy(digest, &h0, sizeof(h0));
memcpy(digest + sizeof(h0), &h1, sizeof(h1));
memcpy(digest + sizeof(h0) + sizeof(h1), &h2, sizeof(h2));
memcpy(digest + sizeof(h0) + sizeof(h1) + sizeof(h2), &h3, sizeof(h3));
//释放内存
free(msg);
}
int main(int argc, char **argv) {
//测试用例
uint8_t digest[16];
md5((uint8_t*)"hello world", strlen("hello world"), digest);
//输出结果
int i;
for (i = 0; i < 16; i++) {
printf("%02x", digest[i]);
}
printf("\n");
return 0;
}
```
这个程序实现了一个简单的MD5哈希函数,可以将任意长度的输入消息转换为一个128位(16字节)的哈希值。在主函数中,我们对字符串“hello world”进行哈希,然后输出哈希结果。
阅读全文