CRC64 Checksums With hash/crc64

Compute CRC-64/ECMA checksums with hash/crc64, append the value to a wire frame, and prove a flipped bit is detected.

GoData Integrity

Code

gosnippet
37 lines
package main

import (
	"encoding/binary"
	"fmt"
	"hash/crc64"
)

func main() {
	payload := []byte("frame=0x2a payload=telemetry")

	// ECMA 多项式表可复用于任意次校验
	table := crc64.MakeTable(crc64.ECMA)
	sum := crc64.Checksum(payload, table)
	fmt.Println("crc64:", sum)

	// 追加 8 字节大端校验和,模拟线上帧格式
	frame := make([]byte, len(payload)+8)
	copy(frame, payload)
	binary.BigEndian.PutUint64(frame[len(payload):], sum)
	fmt.Println("frame bytes:", len(frame))

	// 校验时重新计算前 len(payload) 字节并比较尾部
	got := binary.BigEndian.Uint64(frame[len(payload):])
	fmt.Println("checksum matches:", crc64.Checksum(frame[:len(payload)], table) == got)

	// 翻转一个比特后校验不再匹配
	corrupt := append([]byte(nil), frame...)
	corrupt[0] ^= 0x01
	fmt.Println("corruption caught:", crc64.Checksum(corrupt[:len(payload)], table) != got)

	// New 支持流式写入,适合大文件与网络读取
	h := crc64.New(table)
	h.Write(payload[:6])
	h.Write(payload[6:])
	fmt.Println("streamed equals:", h.Sum64() == sum)
}

How the pieces fit together

Count the function main as the entire surface area of CRC64 Checksums With hash/crc64.

What to watch for

  • The package manager never enters the picture for this snippet.

Using it

The run emits 5 labeled sections — crc64:, frame bytes:, checksum matches:, corruption caught:, streamed equals: — one per step.

Key statements

corrupt := append([]byte(nil), frame...)
frame := make([]byte, len(payload)+8)

Interactive Tools for This Topic

FAQ

What does CRC64 Checksums With hash/crc64 print when run?
The script runs standalone; its 5 labeled outputs include `crc64:`, `frame bytes:`, `checksum matches:`.