feat(hash):增加系列校验和算法实现。

This commit is contained in:
徐涛
2023-07-12 14:59:25 +08:00
parent 0cbeaf050e
commit 29cebf455c
11 changed files with 543 additions and 5 deletions

61
hash/crc32/crc32.go Normal file
View File

@@ -0,0 +1,61 @@
// 提供CRC32校验和计算功能
package crc32
import (
"encoding/hex"
"hash/crc32"
"io"
"os"
)
// 选择一个CRC32校验表
func tableSelect(table string) *crc32.Table {
switch table {
case "IEEE":
return crc32.IEEETable
case "Castagnoli":
return crc32.MakeTable(crc32.Castagnoli)
case "Koopman":
return crc32.MakeTable(crc32.Koopman)
default:
return crc32.IEEETable
}
}
// 计算给定字节数组的CRC32校验和返回字节数组
func CRC32(data []byte, table ...string) []byte {
crcTable := append(table, "IEEE")
hasher := crc32.New(tableSelect(crcTable[0]))
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的CRC32校验和返回十六进制字符串
func CRC32Hex(data []byte, table ...string) string {
return hex.EncodeToString(CRC32(data, table...))
}
// 计算指定文件的CRC32校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
crcTable := append(table, "IEEE")
hasher := crc32.New(tableSelect(crcTable[0]))
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
// 计算指定文件的CRC32校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) {
hash, err := SumFile(file, table...)
if err != nil {
return "", err
}
return hex.EncodeToString(hash), nil
}