feat(hash):增加系列校验和算法实现。

This commit is contained in:
徐涛
2023-07-12 14:59:25 +08:00
parent 0cbeaf050e
commit 29cebf455c
11 changed files with 543 additions and 5 deletions

45
hash/md5/md5.go Normal file
View File

@@ -0,0 +1,45 @@
// 提供MD5散列算法的函数。
package md5
import (
"crypto/md5"
"encoding/hex"
"io"
"os"
)
// 计算给定字节数组的MD5校验和返回字节数组。
func MD5(data []byte) []byte {
hasher := md5.New()
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的MD5校验和返回十六进制字符串。
func MD5Hex(data []byte) string {
return hex.EncodeToString(MD5(data))
}
// 计算一个指定文件的MD5校验和返回字节数组。
func SumFile(file string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
hasher := md5.New()
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
// 计算一个指定文件的MD5校验和返回十六进制字符串。
func SumFileHex(file string) (string, error) {
hash, err := SumFile(file)
if err != nil {
return "", err
}
return hex.EncodeToString(hash), nil
}