feat(hash):增加系列校验和算法实现。
This commit is contained in:
66
hash/crc16/crc16.go
Normal file
66
hash/crc16/crc16.go
Normal file
@@ -0,0 +1,66 @@
|
||||
// 提供CRC16校验和计算功能。
|
||||
package crc16
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/howeyc/crc16"
|
||||
)
|
||||
|
||||
// 根据给定的校验表类型生成对应的校验器
|
||||
func hasherSelect(table string) crc16.Hash16 {
|
||||
switch table {
|
||||
case "CCITT":
|
||||
return crc16.NewCCITT()
|
||||
case "CCITT-FALSE":
|
||||
return crc16.New(crc16.MakeTable(crc16.CCITTFalse))
|
||||
case "SCSI":
|
||||
return crc16.NewSCSI()
|
||||
case "IBM":
|
||||
return crc16.NewIBM()
|
||||
case "MBUS":
|
||||
return crc16.New(crc16.MakeTable(crc16.MBUS))
|
||||
default:
|
||||
return crc16.NewIBM()
|
||||
}
|
||||
}
|
||||
|
||||
// 计算给定字节数组的CRC16校验和,返回字节数组
|
||||
func CRC16(data []byte, table ...string) []byte {
|
||||
crcTable := append(table, "IBM")
|
||||
hasher := hasherSelect(crcTable[0])
|
||||
hasher.Write(data)
|
||||
return hasher.Sum(nil)
|
||||
}
|
||||
|
||||
// 计算给定字节数组的CRC16校验和,返回十六进制字符串
|
||||
func CRC16Hex(data []byte, table ...string) string {
|
||||
return hex.EncodeToString(CRC16(data, table...))
|
||||
}
|
||||
|
||||
// 计算指定文件的CRC16校验和,返回字节数组
|
||||
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, "IBM")
|
||||
hasher := hasherSelect(crcTable[0])
|
||||
if _, err := io.Copy(hasher, f); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hasher.Sum(nil), nil
|
||||
}
|
||||
|
||||
// 计算指定文件的CRC16校验和,返回十六进制字符串
|
||||
func SumFileHex(file string, table ...string) (string, error) {
|
||||
hash, err := SumFile(file, table...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(hash), nil
|
||||
}
|
Reference in New Issue
Block a user