tydata-server/pkg/lzkit/md5/example_test.go
2025-06-08 15:14:34 +08:00

80 lines
2.0 KiB
Go
Raw Permalink 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.

package md5_test
import (
"fmt"
"log"
"tydata-server/pkg/lzkit/md5"
)
func Example() {
// 简单的字符串MD5
hashValue := md5.EncryptString("hello world")
fmt.Println("MD5(hello world):", hashValue)
// 使用链式API
chainHash := md5.New().
Add("hello").
Add(" ").
Add("world").
Sum()
fmt.Println("链式MD5:", chainHash)
// 使用盐值
saltedHash := md5.EncryptStringWithSalt("password123", "main@example.com")
fmt.Println("加盐MD5:", saltedHash)
// 验证哈希
isValid := md5.VerifyMD5("hello world", hashValue)
fmt.Println("验证结果:", isValid)
// 生成短版本的MD5
fmt.Println("16位MD5:", md5.Get16("hello world"))
fmt.Println("8位MD5:", md5.Get8("hello world"))
// 文件MD5计算
filePath := "example.txt" // 这只是示例,实际上这个文件可能不存在
fileHash, err := md5.EncryptFile(filePath)
if err != nil {
// 在实际代码中执行正确的错误处理
log.Printf("计算文件MD5出错: %v", err)
} else {
fmt.Println("文件MD5:", fileHash)
}
// HMAC-MD5
hmacHash := md5.MD5HMAC("重要消息", "secret-key")
fmt.Println("HMAC-MD5:", hmacHash)
}
func ExampleEncryptString() {
hash := md5.EncryptString("HelloWorld")
fmt.Println(hash)
// Output: 68e109f0f40ca72a15e05cc22786f8e6
}
func ExampleMD5_Sum() {
hash := md5.New().
Add("Hello").
Add("World").
Sum()
fmt.Println(hash)
// Output: 68e109f0f40ca72a15e05cc22786f8e6
}
func ExampleEncryptStringWithSalt() {
// 为用户密码加盐,通常使用用户唯一标识(如邮箱)作为盐值
hash := md5.EncryptStringWithSalt("password123", "main@example.com")
fmt.Println("盐值哈希长度:", len(hash))
fmt.Println("是否为有效哈希:", md5.VerifyMD5WithSalt("password123", "main@example.com", hash))
// Output:
// 盐值哈希长度: 32
// 是否为有效哈希: true
}
func ExampleGet16() {
// 获取16位MD5适合不需要完全防碰撞场景
hash := md5.Get16("HelloWorld")
fmt.Println(hash)
// Output: f0f40ca72a15e05c
}