feat(cryptox): 自 go-hua/common 迁入 MD5 摘要工具并独立成包
- 字符串/字节集/文件 MD5,附单元测试、examples/cryptox 例程与包 README
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
# cryptox
|
||||
|
||||
摘要工具:字符串 / 字节集 / 文件的 MD5,返回 32 位十六进制小写。
|
||||
|
||||
> 迁移自 go-hua/common(原 encrypt.go)。
|
||||
|
||||
## 用法
|
||||
|
||||
```go
|
||||
import "git.zeroonesoft.cn/golib/zogo/cryptox"
|
||||
|
||||
s, err := cryptox.GetMd5ByStr("hello") // "5d41402a..."
|
||||
s, err := cryptox.GetMd5ByBytes([]byte("hello"))
|
||||
s, err := cryptox.GetFileMd5("D:/tmp/a.zip") // 读整个文件后计算
|
||||
```
|
||||
|
||||
完整可运行例程:[examples/cryptox/main.go](../examples/cryptox/main.go)
|
||||
|
||||
## 注意
|
||||
|
||||
- MD5 仅用于非安全场景的校验/去重,不用于密码存储或签名。
|
||||
- `GetFileMd5` 为一次性 `os.ReadFile` 全量读入,超大文件注意内存占用。
|
||||
@@ -0,0 +1,43 @@
|
||||
// Package cryptox 摘要工具:字符串/字节集/文件的 MD5(返回 32 位十六进制小写)。
|
||||
package cryptox
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
)
|
||||
|
||||
// GetMd5ByStr 计算字符串的 MD5(返回 32 位十六进制小写)
|
||||
func GetMd5ByStr(str string) (string, error) {
|
||||
h := md5.New()
|
||||
_, err := h.Write([]byte(str))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
s := hex.EncodeToString(h.Sum(nil))
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// GetMd5ByBytes 计算字节集的 MD5(返回 32 位十六进制小写)
|
||||
func GetMd5ByBytes(data []byte) (string, error) {
|
||||
h := md5.New()
|
||||
_, err := h.Write(data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
s := hex.EncodeToString(h.Sum(nil))
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// GetFileMd5 计算文件的 MD5(流式读取,返回 32 位十六进制小写)
|
||||
func GetFileMd5(savePath string) (string, error) {
|
||||
buf, err := os.ReadFile(savePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
str, err := GetMd5ByBytes(buf)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return str, nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package cryptox
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMd5(t *testing.T) {
|
||||
want := "5d41402abc4b2a76b9719d911017c592"
|
||||
got, err := GetMd5ByStr("hello")
|
||||
if err != nil || got != want {
|
||||
t.Errorf("GetMd5ByStr = %q, %v, want %q", got, err, want)
|
||||
}
|
||||
got, err = GetMd5ByBytes([]byte("hello"))
|
||||
if err != nil || got != want {
|
||||
t.Errorf("GetMd5ByBytes = %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFileMd5(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "test.txt")
|
||||
if err := os.WriteFile(path, []byte("hello"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := GetFileMd5(path)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFileMd5: %v", err)
|
||||
}
|
||||
if got != "5d41402abc4b2a76b9719d911017c592" {
|
||||
t.Errorf("GetFileMd5 = %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user