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

73
hash/crc8/crc8.go Normal file
View File

@@ -0,0 +1,73 @@
// 提供CRC8校验和计算功能。
package crc8
import (
"encoding/hex"
"os"
"github.com/sigurn/crc8"
)
// 根据提供的校验表名称生成对应的校验表
func hasherSelect(table string) *crc8.Table {
switch table {
case "CRC8":
return crc8.MakeTable(crc8.CRC8)
case "CDMA2000":
return crc8.MakeTable(crc8.CRC8_CDMA2000)
case "DARC":
return crc8.MakeTable(crc8.CRC8_DARC)
case "DVB-S2":
return crc8.MakeTable(crc8.CRC8_DVB_S2)
case "EBU":
return crc8.MakeTable(crc8.CRC8_EBU)
case "I-CODE":
return crc8.MakeTable(crc8.CRC8_I_CODE)
case "ITU":
return crc8.MakeTable(crc8.CRC8_ITU)
case "MAXIM":
return crc8.MakeTable(crc8.CRC8_MAXIM)
case "ROHC":
return crc8.MakeTable(crc8.CRC8_ROHC)
case "WCDMA":
return crc8.MakeTable(crc8.CRC8_WCDMA)
default:
return crc8.MakeTable(crc8.CRC8)
}
}
// 计算给定字节数组的CRC8校验和返回字节数组
func CRC8(data []byte, table ...string) []byte {
crcTable := append(table, "CRC8")
return []byte{crc8.Checksum(data, hasherSelect(crcTable[0]))}
}
// 计算给定字节数组的CRC8校验和返回十六进制字符串
func CRC8Hex(data []byte, table ...string) string {
return hex.EncodeToString(CRC8(data, table...))
}
// 计算指定文件的CRC8校验和返回字节数组
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, "CRC8")
var buf = make([]byte, 0)
if _, err := f.Read(buf); err != nil {
return nil, err
}
return []byte{crc8.Checksum(buf, hasherSelect(crcTable[0]))}, nil
}
// 计算指定文件的CRC8校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) {
crc, err := SumFile(file, table...)
if err != nil {
return "", err
}
return hex.EncodeToString(crc), nil
}