feat(hash):增加系列校验和算法实现。
This commit is contained in:
81
hash/sha256/sha256.go
Normal file
81
hash/sha256/sha256.go
Normal file
@@ -0,0 +1,81 @@
|
||||
// 提供Sha256系列散列算法函数和校验和函数。
|
||||
package sha256
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"hash"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// 根据给定的位数返回一个散列算法的Hash实例。
|
||||
func hasherSelect(bitSize int) hash.Hash {
|
||||
switch bitSize {
|
||||
case 224:
|
||||
return sha256.New224()
|
||||
default:
|
||||
return sha256.New()
|
||||
}
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Sha256校验和,返回字节数组。
|
||||
func Sha256(data []byte) []byte {
|
||||
hasher := hasherSelect(256)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Sha256/224校验和,返回字节数组。
|
||||
func Sha256_224(data []byte) []byte {
|
||||
hasher := hasherSelect(224)
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Sha256校验和,返回十六进制字符串。
|
||||
func Sha256Hex(data []byte) string {
|
||||
return hex.EncodeToString(Sha256(data))
|
||||
}
|
||||
|
||||
// 计算给定字节数组的Sha256/224校验和,返回十六进制字符串。
|
||||
func Sha256_224Hex(data []byte) string {
|
||||
return hex.EncodeToString(Sha256_224(data))
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个字节数组的Sha256校验和,返回字节数组。
|
||||
func Sum256(data []byte, bitSize ...int) []byte {
|
||||
length := append(bitSize, 256)
|
||||
hasher := hasherSelect(length[0])
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个字节数组的Sha256校验和,返回十六进制字符串。
|
||||
func Sum256Hex(data []byte, bitSize ...int) string {
|
||||
return hex.EncodeToString(Sum256(data, bitSize...))
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个文件的Sha256校验和,返回字节数组。
|
||||
func SumFile256(file string, bitSize ...int) ([]byte, error) {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
hasher := hasherSelect(bitSize[0])
|
||||
if _, err := io.Copy(hasher, f); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hasher.Sum(nil), nil
|
||||
}
|
||||
|
||||
// 根据给定位数计算一个文件的Sha256校验和,返回十六进制字符串。
|
||||
func SumFile256Hex(file string, bitSize ...int) (string, error) {
|
||||
hash, err := SumFile256(file, bitSize...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(hash), nil
|
||||
}
|
Reference in New Issue
Block a user