MD5算法 c/c++实现完整代码
时间: 2023-07-26 10:07:06 浏览: 178
这是一个简单的 C++ 实现 MD5 算法的代码示例:
```cpp
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
typedef unsigned int uint32_t;
// 左移位数表
const uint32_t S[] = {
7, 12, 17, 22,
7, 12, 17, 22,
7, 12, 17, 22,
7, 12, 17, 22
};
// 常数表
const uint32_t K[] = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
};
// 各轮移位数表
const uint32_t shift_table[] = {
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15,
1, 6, 11, 0,
5, 10, 15, 4,
9, 14, 3, 8,
13, 2, 7, 12,
5, 9, 14, 0,
4, 11, 15, 3,
8, 9, 14, 5,
12, 2, 7, 10,
0, 6, 13, 15,
9, 11, 3, 8,
12, 2, 7, 1
};
// 左移函数
inline uint32_t left_rotate(uint32_t x, uint32_t c) {
return (x << c) | (x >> (32 - c));
}
void md5(uint32_t *input, uint32_t length, uint32_t *digest) {
// 初始化
uint32_t A = 0x67452301;
uint32_t B = 0xefcdab89;
uint32_t C = 0x98badcfe;
uint32_t D = 0x10325476;
for (uint32_t i = 0; i < length; i += 16) {
uint32_t a = A, b = B, c = C, d = D;
uint32_t *chunk = input + i;
// 循环压缩
for (uint32_t 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 + left_rotate((a + F + K[j] + chunk[g]), S[j]);
a = temp;
}
A += a;
B += b;
C += c;
D += d;
}
digest[0] = A;
digest[1] = B;
digest[2] = C;
digest[3] = D;
}
int main() {
char *str = "hello, world!";
uint32_t len = strlen(str);
uint32_t *input = new uint32_t[(len + 8) / 4];
memcpy(input, str, len);
input[len / 4] |= 0x80 << ((len % 4) * 8);
input[(len + 8) / 4 - 2] = len * 8;
uint32_t digest[4];
md5(input, (len + 64) / 64 * 16, digest);
printf("%08x%08x%08x%08x\n", digest[0], digest[1], digest[2], digest[3]);
delete[] input;
return 0;
}
```
这个程序计算字符串 "hello, world!" 的 MD5 值,并输出结果。注:这个实现并没有对输入进行预处理,而是直接将其视为一连串的 8 位字符。在实际使用中,需要对输入进行填充和预处理。
阅读全文