MD5加密算法C语言实现
时间: 2023-06-08 13:05:42 浏览: 157
MD5加密算法 C语言实现
4星 · 用户满意度95%
可以使用以下代码实现MD5加密算法的C语言实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
void md5(char *initial_msg, size_t initial_len, char *output) {
uint8_t msg[initial_len];
uint32_t i, j, k;
uint32_t h0, h1, h2, h3;
h0 = 0x67452301;
h1 = 0xEFCDAB89;
h2 = 0x98BADCFE;
h3 = 0x10325476;
uint32_t *msg32;
size_t new_len, offset;
for (i = 0; i < initial_len; ++i) {
msg[i] = initial_msg[i];
}
new_len = ((((uint64_t)initial_len + 8) / 64) + 1) * 64;
msg32 = calloc(new_len, 1);
for (i = 0; i < initial_len; ++i) {
msg32[i >> 2] |= msg[i] << ((i % 4) * 8);
}
msg32[i >> 2] |= 0x80 << ((i % 4) * 8);
msg32[new_len/4 - 2] = initial_len*8;
for (i = 0; i < new_len; i += 64) {
uint32_t a = h0, b = h1, c = h2, d = h3;
uint32_t chunk[16];
for (j = 0; j < 16; ++j) {
chunk[j] = msg32[i/4 + j];
}
for (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 = b + LEFTROTATE((a + f + 0x5A827999 + chunk[g]), 12);
a = temp;
}
h0 += a;
h1 += b;
h2 += c;
h3 += d;
}
sprintf(output, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
(h0>>24)&0xff, (h0>>16)&0xff, (h0>>8)&0xff, h0&0xff,
(h1>>24)&0xff, (h1>>16)&0xff, (h1>>8)&0xff, h1&0xff,
(h2>>24)&0xff, (h2>>16)&0xff, (h2>>8)&0xff, h2&0xff,
(h3>>24)&0xff, (h3>>16)&0xff, (h3>>8)&0xff, h3&0xff);
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("usage: %s 'string'\n", argv[0]);
return 1;
}
char output[33];
md5(argv[1], strlen(argv[1]), output);
printf("%s\n", output);
return 0;
}
```
请注意,这只是一种实现方法,如果需要用于实际项目中,请务必进行全面的测试和评估,并采取适当的安全措施。
阅读全文