82 lines
2.2 KiB
Go
82 lines
2.2 KiB
Go
// 提供Sha256系列散列算法函数和校验和函数。
|
||
package sha256
|
||
|
||
import (
|
||
"crypto/sha256"
|
||
"encoding/hex"
|
||
"fmt"
|
||
"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 {
|
||
hasher := hasherSelect(append(bitSize, 256)[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, fmt.Errorf("未能打开指定文件,%w", err)
|
||
}
|
||
defer f.Close()
|
||
|
||
hasher := hasherSelect(append(bitSize, 256)[0])
|
||
if _, err := io.Copy(hasher, f); err != nil {
|
||
return nil, fmt.Errorf("未能读取指定文件的内容,%w", 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
|
||
}
|