feat(hash):增加系列校验和算法实现。
This commit is contained in:
98
hash/sha512/sha512.go
Normal file
98
hash/sha512/sha512.go
Normal file
@@ -0,0 +1,98 @@
|
||||
// 提供Sha512系列散列算法函数和校验和函数。
|
||||
package sha512
|
||||
|
||||
import (
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"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, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
length := append(bitSize, 512)
|
||||
var hasher = hasherSelect(length[0])
|
||||
if _, err := io.Copy(hasher, f); err != nil {
|
||||
return nil, 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
|
||||
}
|
Reference in New Issue
Block a user