ag_toolsbox/hash/sha512/sha512.go

100 lines
2.6 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.

// 提供Sha512系列散列算法函数和校验和函数。
package sha512
import (
"crypto/sha512"
"encoding/hex"
"fmt"
"hash"
"io"
"os"
)
// 根据给定的位数返回一个散列算法的Hash实例。
func hasherSelect(bitSize int) hash.Hash {
switch bitSize {
case 224:
return sha512.New512_224()
case 256:
return sha512.New512_256()
case 384:
return sha512.New384()
default:
return sha512.New()
}
}
// 计算给定字节数组的Sha512校验和返回字节数组。
func Sha512(data []byte) []byte {
hash := hasherSelect(512)
hash.Write(data)
return hash.Sum(nil)
}
// 计算给定字节数组的Sha512/384校验和返回字节数组。
func Sha512_384(data []byte) []byte {
hash := hasherSelect(384)
hash.Write(data)
return hash.Sum(nil)
}
// 计算给定字节数组的Sha512/256校验和返回字节数组。
func Sha512_256(data []byte) []byte {
hash := hasherSelect(256)
hash.Write(data)
return hash.Sum(nil)
}
// 计算给定字节数组的Sha512校验和返回十六进制字符串。
func Sha512Hex(data []byte) string {
return hex.EncodeToString(Sha512(data))
}
// 计算给定字节数组的Sha512/384校验和返回十六进制字符串。
func Sha512_384Hex(data []byte) string {
return hex.EncodeToString(Sha512_384(data))
}
// 计算给定字节数组的Sha512/256校验和返回十六进制字符串。
func Sha512_256Hex(data []byte) string {
return hex.EncodeToString(Sha512_256(data))
}
// 根据给定位数计算指定字节数组的校验和,返回字节数组。
func Sum512(data []byte, bitSize ...int) []byte {
length := append(bitSize, 512)
var hasher = hasherSelect(length[0])
hasher.Write(data)
return hasher.Sum(nil)
}
// 根据给定位数计算指定字节数组的校验和,返回十六进制字符串。
func Sum512Hex(data []byte, bitSize ...int) string {
return hex.EncodeToString(Sum512(data, bitSize...))
}
// 根据给定位数计算指定文件的校验和,返回字节数组。
func SumFile512(path string, bitSize ...int) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
length := append(bitSize, 512)
var hasher = hasherSelect(length[0])
if _, err := io.Copy(hasher, f); err != nil {
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}
// 根据给定位数计算指定文件的校验和,返回十六进制字符串。
func SumFile512Hex(path string, bitSize ...int) (string, error) {
data, err := SumFile512(path, bitSize...)
if err != nil {
return "", err
}
return hex.EncodeToString(data), nil
}