md5哈希算法c实现
时间: 2023-10-25 09:09:46 浏览: 100
MD5是一种常用的哈希算法,它将任意长度的消息压缩成一个128位的消息摘要(或称为指纹)。下面是一个简单的C语言实现:
```c
#include <stdio.h>
#include <stdlib.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, uint8_t *digest) {
uint32_t h0, h1, h2, h3;
uint8_t *msg = NULL;
// 初始化常量
uint32_t k[] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
// 初始化变量
uint32_t a, b, c, d, i, j;
// 初始化消息
size_t new_len = ((((initial_len + 8) / 64) + 1) * 64) - 8;
msg = calloc(new_len + 64, 1);
memcpy(msg, initial_msg, initial_len);
msg[initial_len] = 128;
uint32_t bits_len = 8 * initial_len;
memcpy(msg + new_len, &bits_len, 4);
// 初始化哈希值
h0 = 0x67452301;
h1 = 0xefcdab89;
h2 = 0x98badcfe;
h3 = 0x10325476;
// 处理消息
for (i = 0; i < new_len; i += 64) {
a = h0;
b = h1;
c = h2;
d = h3;
uint32_t *chunk = (uint32_t *)(msg + i);
uint32_t *w = (uint32_t *)calloc(64, 1);
for (j = 0; j < 16; j++) {
w[j] = chunk[j];
}
for (j = 16; j < 64; j++) {
uint32_t s0 = LEFTROTATE(w[j - 15], 7) ^ LEFTROTATE(w[j - 15], 18) ^ (w[j - 15] >> 3);
uint32_t s1 = LEFTROTATE(w[j - 2], 17) ^ LEFTROTATE(w[j - 2], 19) ^ (w[j - 2] >> 10);
w[j] = w[j - 16] + s0 + w[j - 7] + s1;
}
for (j = 0; j < 64; j++) {
uint32_t s0 = LEFTROTATE(a, 12) ^ LEFTROTATE(a, 25) ^ LEFTROTATE(a, 27);
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
uint32_t t2 = s0 + maj;
uint32_t s1 = LEFTROTATE(d, 5) ^ LEFTROTATE(d, 13) ^ LEFTROTATE(d, 22);
uint32_t ch = (d & b) ^ ((~d) & c);
uint32_t t1 = h[j] + s1 + ch + k[j] + w[j];
d = c;
c = b;
b = a;
a = t1 + t2;
}
h0 += a;
h1 += b;
h2 += c;
h3 += d;
free(w);
}
// 生成摘要
memcpy(digest, &h0, 4);
memcpy(digest + 4, &h1, 4);
memcpy(digest + 8, &h2, 4);
memcpy(digest + 12, &h3, 4);
free(msg);
}
int main(int argc, char **argv) {
uint8_t digest[16];
char *msg = "hello world";
md5((uint8_t *)msg, strlen(msg), digest);
printf("MD5(\"%s\") = ", msg);
for (int i = 0; i < 16; i++) {
printf("%02x", digest[i]);
}
printf("\n");
return 0;
}
```
这个实现使用了标准的MD5算法,包括初始化常量、初始化变量、消息处理和生成摘要等步骤。你可以将任意长度的消息传递给`md5`函数,它将返回一个16字节的摘要。
阅读全文