一、原理
MD5(Message Digest Algorithm 5)是一种广泛使用的加密哈希函数,由罗纳德·李维斯特(Ronald Rivest)于1991年设计。MD5的目的是从任意长度的数据中产生一个128位(16字节)的哈希值,通常表示为32个十六进制字符。MD5的设计使其用于确保数据的完整性,常见于文件校验、数字签名等场景。
MD5的工作流程包括以下几个主要步骤:
-
填充:首先对消息进行填充,以使其长度(以位计)模512为448。填充始终以1开始,后跟0,直到满足长度要求。
-
追加长度:在填充的消息后追加一个64位的长度字段,表示原始消息的长度(以位计)。这保证了即使两个不同的消息在填充后内容相同,它们的长度字段也会不同,从而导致不同的哈希值。
-
初始化MD5缓冲区:算法使用4个32位的寄存器(通常表示为A, B, C, D),并将它们初始化为特定的常数值。
-
处理消息块:算法接着将填充后的消息分成512位的块,并对每个块进行处理。每个块分为16个32位的子块。
-
四轮主循环:每个512位的消息块经过四轮循环处理,每轮包含16个相似的操作,这些操作基于非线性函数(F, G, H, I),每一轮使用不同的函数。这些函数依赖于其输入的位操作,并结合了加法、循环左移以及基于消息块的部分内容。
-
输出:处理完所有的消息块后,四个寄存器中的值合并成一个128位的散列值,这就是最终的输出。
MD5曾经被认为是相对安全的加密算法,但自2000年以来,研究人员发现了多种攻击方法,可以相对容易地找到两个不同的输入消息,它们产生相同的MD5哈希(即产生冲突)。因此,尽管MD5在许多遗留系统中仍然被使用,但现在通常不推荐用于需要高安全性的加密应用中,更安全的哈希函数如SHA-256和SHA-3等已经取代了MD5的许多用途。
二、C/C++实现
MD5.h
#pragma once
#ifndef MD5_H
#define MD5_H
#include <cstddef> // 对于 size_t
#include <cstdint> // 对于 uint32_t 和 uint8_t
// 定义 MD5 块大小
#define MD5_BLOCK_SIZE 64
// MD5 上下文结构
typedef struct hash_context {
uint8_t buffer[MD5_BLOCK_SIZE]; // 数据块缓冲区
uint32_t state[5]; // 状态数组,存储中间值的状态
uint32_t total[2]; // 位数计数器,当前已处理数据的长度
} hash_context;
// MD5 算法的主要函数声明
void hash_start(hash_context* ctx);
void hash_update(hash_context* ctx, const uint8_t* data, size_t len);
void hash_finish(hash_context* ctx, uint8_t* digest);
void MD5_Transform(uint32_t state[4], const uint8_t block[MD5_BLOCK_SIZE]);
void MD5_Encode(uint8_t* output, const uint32_t* input, size_t len);
void MD5_Decode(uint32_t* output, const uint8_t* input, size_t len);
#endif
MD5.CPP
#include <cstring>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <string>
//#include <iostream>
#include <cstdint> // 用于uint32_t和uint8_t
#include "MD5.h"
//using namespace std;
#define MD5_BLOCK_SIZE 64
// 辅助函数定义
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (uint32_t)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (uint32_t)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (uint32_t)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (uint32_t)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
static const uint8_t PADDING[64] = { 0x80, 0 };
typedef struct {
uint8_t buffer[64];
uint32_t state[4];
uint32_t count[2];
} MD5_CTX;
void hash_start(hash_context* ctx) {
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xC3D2E1F0;
ctx->total[0] = 0;
ctx->total[1] = 0;
}
void hash_update(hash_context* ctx, const uint8_t* data, size_t len) {
uint32_t i, index, partLen;
index = (uint32_t)((ctx->total[0] >> 3) & 0x3F);
if ((ctx->total[0] += (uint32_t)len << 3) < (uint32_t)len << 3)
ctx->total[1]++;
ctx->total[1] += (uint32_t)len >> 29;
partLen = 64 - index;
if (len >= partLen) {
memcpy(&ctx->buffer[index], data, partLen);
MD5_Transform(ctx->state, ctx->buffer);
for (i = partLen; i + 63 < len; i += 64) {
MD5_Transform(ctx->state, &data[i]);
}
index = 0;
}
else {
i = 0;
}
memcpy(&ctx->buffer[index], &data[i], len - i);
}
void hash_finish(hash_context* ctx, uint8_t* digest) {
uint8_t bits[8];
uint32_t index, padLen;
MD5_Encode(bits, ctx->total, 8);
index = (uint32_t)((ctx->total[0] >> 3) & 0x3F);
padLen = (index < 56) ? (56 - index) : (120 - index);
hash_update(ctx, PADDING, padLen);
hash_update(ctx, bits, 8);
MD5_Encode(digest, ctx->state, 16);
memset(ctx, 0, sizeof(*ctx));
}
// MD5_Transform 函数实现
static void MD5_Transform(uint32_t state[4], const uint8_t block[MD5_BLOCK_SIZE])
{
uint32_t a = state[0], b = state[1], c = state[2], d = state[3], x[16];
MD5_Decode(x, block, 64);
//Round 1 使用 FF 函数和一个系列的常数和数据块索引。
//Round 2 使用 GG 函数,常数和数据块索引按照MD5算法规范变化。
//Round 3 使用 HH 函数,常数和数据块索引继续变化。
//Round 4 使用 II 函数,再次变化常数和数据块索引。
// Round 1
FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ //预定义常数是由正弦函数的值计算得出的,确保每次操作都略有不同,从而增加了哈希过程的熵和不可预测性。
FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */
FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */
FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */
FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */
FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */
FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */
FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */
FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */
FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */
FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
// Round 2
GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */
GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */
GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */
GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */
GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */
GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */
GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */
GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */
GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */
GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */
GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
// Round 3
HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */
HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */
HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */
HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */
HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */
HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */
HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */
HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */
HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */
HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */
// Round 4
II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */
II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */
II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */
II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */
II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */
II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */
II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */
II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */
II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */
II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
// 清除敏感信息
memset(x, 0, sizeof(x));
}
// MD5_Encode 函数实现
static void MD5_Encode(uint8_t* output, const uint32_t* input, size_t len) {
for (size_t i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (uint8_t)(input[i] & 0xff);
output[j + 1] = (uint8_t)((input[i] >> 8) & 0xff);
output[j + 2] = (uint8_t)((input[i] >> 16) & 0xff);
output[j + 3] = (uint8_t)((input[i] >> 24) & 0xff);
}
}
// MD5_Decode 函数实现
static void MD5_Decode(uint32_t* output, const uint8_t* input, size_t len) {
for (size_t i = 0, j = 0; j < len; i++, j += 4) {
output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j + 1]) << 8) |
(((uint32_t)input[j + 2]) << 16) | (((uint32_t)input[j + 3]) << 24);
}
}
/************************** 宏定义 **************************/
#define DATA_SIZE 1073741824
#define ROUNDS 1
/************************* 函数定义 *************************/
uint8_t data[DATA_SIZE];
int main()
{
hash_context ctx;
uint8_t hash[20];
clock_t start, end;
// 生成随机数据填充到data数组中
for (int i = 0; i < DATA_SIZE; i++)
{
data[i] = rand() & 0xFF;
}
// 开始计时
start = clock();
for (int i = 0; i < ROUNDS; i++)
{
hash_start(&ctx);
hash_update(&ctx, data, DATA_SIZE);
hash_finish(&ctx, hash);
}
// 结束计时
end = clock();
// 计算总运行时间和每秒处理的数据量
double time = (double)(end - start) / CLOCKS_PER_SEC;
double computing_speed = (DATA_SIZE * ROUNDS * (unsigned long long)8 / 1000 / 1000) / time;
printf("运行时间: %f seconds\n", time);
printf("运算速度: %f Mbps\n", computing_speed);
return 0;
}
MD5函数实现,将字符串转换为MD5哈希
//string MD5(const string& input) {
// hash_context ctx;
// uint8_t digest[16]; // MD5哈希是16字节
// char buffer[33]; // 存储32个字符的哈希值和一个终止符
//
// hash_start(&ctx);
// hash_update(&ctx, reinterpret_cast<const uint8_t*>(input.c_str()), input.length());
// hash_finish(&ctx, digest);
//
// // 将16字节的哈希转换为32个字符的十六进制字符串
// for (int i = 0; i < 16; i++) {
// sprintf_s(buffer + i * 2, 3, "%02x", digest[i]); // 每次写入3个字符(2个十六进制数字和一个终止符)
// }
//
// return string(buffer);
//}
//int main() {
// // 测试用例
// struct TestCase {
// string input;
// string expectedOutput;
// };
//
// TestCase testCases[] = {
// {"", "d41d8cd98f00b204e9800998ecf8427e"},
// {"a", "0cc175b9c0f1b6a831c399e269772661"},
// {"abc", "900150983cd24fb0d6963f7d28e17f72"},
// {"message digest", "f96b697d7cb7938d525a2f31aaf161d0"},
// {"abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b"},
// // 添加更多测试用例
// };
//
// // 执行测试
// bool allTestsPassed = true;
// for (const auto& testCase : testCases) {
// string output = MD5(testCase.input); // 调用您的 MD5 函数
// if (output != testCase.expectedOutput) {
// cout << "Test failed for input: " << testCase.input << endl;
// cout << "Expected: " << testCase.expectedOutput << ", Got: " << output << endl;
// allTestsPassed = false;
// break; // 如果有一个测试失败,就停止测试
// }
// }
//
// if (allTestsPassed) {
// cout << "All tests passed." << endl;
// }
// else {
// cout << "Some tests failed." << endl;
// }
//
// return 0;
//}