ag_toolsbox/hash/sha1/sha1.go

47 lines
1.1 KiB
Go
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.

// 提供Sha1系列散列算法函数和校验和函数
package sha1
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"os"
)
// 计算给定字节数组的Sha1校验和返回字节数组
func Sha1(data []byte) []byte {
hasher := sha1.New()
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的Sha1校验和返回十六进制字符串
func Sha1Hex(data []byte) string {
return hex.EncodeToString(Sha1(data))
}
// 计算一个指定文件的Sha1校验和返回字节数组
func SumFile(file string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
hasher := sha1.New()
if _, err := io.Copy(hasher, f); err != nil {
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}
// 计算一个指定文件的Sha1校验和返回十六进制字符串
func SumFileHex(file string) (string, error) {
hash, err := SumFile(file)
if err != nil {
return "", err
}
return hex.EncodeToString(hash), nil
}