// 提供CRC64校验和计算功能。 package crc64 import ( "encoding/hex" "fmt" "hash/crc64" "io" "os" ) // 选择一个CRC64校验表。 func tableSelect(table string) *crc64.Table { switch table { case "ECMA": return crc64.MakeTable(crc64.ECMA) case "ISO": return crc64.MakeTable(crc64.ISO) default: return crc64.MakeTable(crc64.ISO) } } // 计算给定字节数组的CRC64校验和,返回字节数组。 func CRC64(data []byte, table ...string) []byte { crcTable := append(table, "ISO") hasher := crc64.New(tableSelect(crcTable[0])) hasher.Write(data) return hasher.Sum(nil) } // 计算给定字节数组的CRC64校验和,返回十六进制字符串。 func CRC64Hex(data []byte, table ...string) string { return hex.EncodeToString(CRC64(data, table...)) } // 计算一个指定文件的CRC64校验和,返回字节数组。 func SumFile(file string, table ...string) ([]byte, error) { f, err := os.Open(file) if err != nil { return nil, fmt.Errorf("未能打开指定文件,%w", err) } defer f.Close() crcTable := append(table, "ISO") hasher := crc64.New(tableSelect(crcTable[0])) if _, err := io.Copy(hasher, f); err != nil { return nil, fmt.Errorf("未能读取指定文件的内容,%w", err) } return hasher.Sum(nil), nil } // 计算一个指定文件的CRC64校验和,返回十六进制字符串。 func SumFileHex(file string, table ...string) (string, error) { hash, err := SumFile(file, table...) if err != nil { return "", err } return hex.EncodeToString(hash), nil }