qnc-server-tob/pkg/lzkit/md5/README.md
2025-04-08 12:49:19 +08:00

107 lines
2.5 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.

# MD5 工具包
这个包提供了全面的 MD5 哈希功能,包括字符串加密、文件加密、链式操作、加盐哈希等。
## 主要功能
- 字符串和字节切片的 MD5 哈希计算
- 文件 MD5 哈希计算(支持大文件分块处理)
- 链式 API支持构建复杂的哈希内容
- 带盐值的 MD5 哈希,提高安全性
- 哈希验证功能
- 16 位和 8 位 MD5 哈希(短版本)
- HMAC-MD5 实现,增强安全性
## 使用示例
### 基本使用
```go
// 计算字符串的MD5哈希
hash := md5.EncryptString("hello world")
fmt.Println(hash) // 5eb63bbbe01eeed093cb22bb8f5acdc3
// 计算字节切片的MD5哈希
bytes := []byte("hello world")
hash = md5.EncryptBytes(bytes)
// 计算文件的MD5哈希
fileHash, err := md5.EncryptFile("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(fileHash)
```
### 链式 API
```go
// 创建一个新的MD5实例并添加内容
hash := md5.New().
Add("hello").
Add(" ").
Add("world").
Sum()
fmt.Println(hash) // 5eb63bbbe01eeed093cb22bb8f5acdc3
// 或者从字符串初始化
hash = md5.FromString("hello").
Add(" world").
Sum()
// 从字节切片初始化
hash = md5.FromBytes([]byte("hello")).
AddBytes([]byte(" world")).
Sum()
```
### 安全性增强
```go
// 使用盐值加密(提高安全性)
hashedPassword := md5.EncryptStringWithSalt("password123", "user@example.com")
// 使用前缀加密
hashedValue := md5.EncryptStringWithPrefix("secret-data", "prefix-")
// 验证带盐值的哈希
isValid := md5.VerifyMD5WithSalt("password123", "user@example.com", hashedPassword)
// 使用HMAC-MD5提高安全性
hmacHash := md5.MD5HMAC("message", "secret-key")
```
### 短哈希值
```go
// 获取16位MD532位MD5的中间部分
hash16 := md5.Get16("hello world")
fmt.Println(hash16) // 中间16个字符
// 获取8位MD5
hash8 := md5.Get8("hello world")
fmt.Println(hash8) // 中间8个字符
```
### 文件验证
```go
// 验证文件MD5是否匹配
match, err := md5.VerifyFileMD5("path/to/file.txt", "expected-hash")
if err != nil {
log.Fatal(err)
}
if match {
fmt.Println("文件MD5校验通过")
} else {
fmt.Println("文件MD5校验失败")
}
```
## 注意事项
1. MD5 主要用于校验,不适合用于安全存储密码等敏感信息
2. 如果用于密码存储,请务必使用加盐处理并考虑使用更安全的算法
3. 处理大文件时请使用`EncryptFileChunk`以优化性能
4. 返回的 MD5 哈希值都是 32 位的小写十六进制字符串(除非使用 Get16/Get8 函数)