RTU_ALL_AI/docs/public/libmd5/API-libmd5.md

82 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# libmd5 — MD5 消息摘要 API 参考
## 模块概述
libmd5 实现了 RFC 1321 定义的 MD5 消息摘要算法。128 位输出,支持流式输入
(分多次调用 `md5_update`)。提供 `md5_string` 便捷函数一步完成字符串 MD5 计算。
## 数据结构
```c
typedef struct
{
uint32_t state[4]; // A, B, C, D 四个 32 位状态寄存器
uint32_t count[2]; // 位计数(低 32 位, 高 32 位)
unsigned char buf[64]; // 待处理数据缓冲区64 字节)
} stru_md5_ctx;
```
## 接口函数
### md5_start(ctx)
```c
void md5_start(stru_md5_ctx *ctx);
```
初始化上下文,设置 RFC 1321 标准魔数:
`A=0x67452301 B=0xefcdab89 C=0x98badcfe D=0x10325476`
### md5_update(ctx, data, len)
```c
void md5_update(stru_md5_ctx *ctx, const unsigned char *data, int len);
```
输入数据,可多次调用支持流式处理。内部按 64 字节分块,填满即变换。
### md5_final(ctx, result)
```c
void md5_final(stru_md5_ctx *ctx, unsigned char result[16]);
```
完成计算,输出 16 字节 MD5 摘要。内部自动填充 0x80+零+位计数。
### md5_string(input, output)
```c
void md5_string(const char *input, char output[33]);
```
单次调用便捷函数:输入字符串 → 输出 32 字符大写十六进制 + '\0'。
## 使用示例
```c
#include "myMd5.h"
#include <stdio.h>
#include <string.h>
int main(void)
{
// 方式 1: 单次调用
char hex[33];
md5_string("hello", hex);
printf("MD5(hello) = %s\n", hex);
// 输出: MD5(hello) = 5D41402ABC4B2A76B9719D911017C592
// 方式 2: 流式计算(大文件场景)
stru_md5_ctx ctx;
unsigned char digest[16];
md5_start(&ctx);
md5_update(&ctx, (unsigned char *)"hello ", 6);
md5_update(&ctx, (unsigned char *)"world", 5);
md5_final(&ctx, digest);
printf("流式: ");
for (int i = 0; i < 16; i++) printf("%02X", digest[i]);
printf("\n");
return 0;
}
```
## 依赖关系
- **依赖**: 无
- **被依赖**: 文件校验、协议认证 等模块