# hash/crc32

`hash/crc32` 計算 32 位元的循環冗餘校驗碼（CRC-32），用來快速檢查資料在傳輸或儲存時有沒有意外損毀。

## 這個套件做什麼

CRC（cyclic redundancy check，循環冗餘校驗）就像包裹上的封條：寄出前算一個 4 位元組的數字貼上去，收到後再算一次，兩者不同就代表內容在路上壞了。gzip、zip、PNG、乙太網路都用它。

什麼時候用：

- 檔案下載、網路封包、磁碟區塊的完整性檢查
- 讀寫自訂二進位格式時，附上校驗碼偵測損毀

注意：CRC32 只能抓「意外」的錯誤，任何人都能刻意造出相同 CRC 的資料。要防竄改請改用 [crypto/sha256](/pkg-crypto-sha256) 或 [crypto/hmac](/pkg-crypto-hmac)。

CRC32 有好幾種「多項式」（polynomial），可以想成不同的計算規則，算出來的值彼此不通用：

| 常數 | 用在哪裡 |
| --- | --- |
| `crc32.IEEE` | 最常見：gzip、zip、PNG、乙太網路 |
| `crc32.Castagnoli` | iSCSI、ext4、許多儲存系統；偵錯能力較好，新 CPU 有硬體加速 |
| `crc32.Koopman` | 偵錯能力較好，較少見 |

它實作了 [hash](/pkg-hash) 套件的 `hash.Hash32` 介面。

## 匯入

```go
import "hash/crc32"
```

## 常用 API

### ChecksumIEEE

最簡單的用法：資料已經在記憶體裡，直接算出 IEEE 多項式的 CRC32。回傳 `uint32`。

簽名：

```go
func ChecksumIEEE(data []byte) uint32
```

範例：

```go
package main

import (
	"fmt"
	"hash/crc32"
)

func main() {
	data := []byte("hello, gopher")
	sum := crc32.ChecksumIEEE(data)
	fmt.Printf("%d\n", sum)
	fmt.Printf("0x%08x\n", sum)

	data[0] = 'H'
	fmt.Printf("0x%08x (只改一個字母)\n", crc32.ChecksumIEEE(data))
}
```

輸出：

```text
490200784
0x1d37ded0
0xae499525 (只改一個字母)
```

### MakeTable 與 Checksum

要用 IEEE 以外的多項式，先用 `MakeTable` 建一張查找表（`*Table`），再交給 `Checksum`。建表有成本，請建一次後重複使用，例如存在套件層級變數。IEEE 已經有現成的 `crc32.IEEETable`。

簽名：

```go
func MakeTable(poly uint32) *Table
func Checksum(data []byte, tab *Table) uint32
```

範例：

```go
package main

import (
	"fmt"
	"hash/crc32"
)

var castagnoli = crc32.MakeTable(crc32.Castagnoli)

func main() {
	data := []byte("hello, gopher")

	fmt.Printf("IEEE       0x%08x\n", crc32.Checksum(data, crc32.IEEETable))
	fmt.Printf("Castagnoli 0x%08x\n", crc32.Checksum(data, castagnoli))
	fmt.Printf("Koopman    0x%08x\n", crc32.Checksum(data, crc32.MakeTable(crc32.Koopman)))
	fmt.Println(crc32.Checksum(data, crc32.IEEETable) == crc32.ChecksumIEEE(data))
}
```

輸出：

```text
IEEE       0x1d37ded0
Castagnoli 0x7eed3a96
Koopman    0x6ce5c0c8
true
```

### NewIEEE 與 New 串流計算

資料很大、或是一段一段來時，用 `NewIEEE()`／`New(tab)` 建立一個 `hash.Hash32`，再用 `Write` 或 `io.Copy` 餵資料，最後呼叫 `Sum32()`。不必把整個檔案讀進記憶體。

簽名：

```go
func NewIEEE() hash.Hash32
func New(tab *Table) hash.Hash32
```

範例：

```go
package main

import (
	"fmt"
	"hash/crc32"
	"io"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	dir, err := os.MkdirTemp("", "crc32")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)

	path := filepath.Join(dir, "big.txt")
	content := strings.Repeat("gopher\n", 10000)
	if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
		fmt.Println(err)
		return
	}

	f, err := os.Open(path)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	h := crc32.NewIEEE()
	n, err := io.Copy(h, f)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("read %d bytes, crc32=0x%08x\n", n, h.Sum32())
	fmt.Println("match:", h.Sum32() == crc32.ChecksumIEEE([]byte(content)))

	c := crc32.New(crc32.MakeTable(crc32.Castagnoli))
	c.Write([]byte(content))
	fmt.Printf("castagnoli=0x%08x\n", c.Sum32())
}
```

輸出：

```text
read 70000 bytes, crc32=0x21690317
match: true
castagnoli=0xee786f6a
```

### Update 累加計算

`Update` 接收「目前為止的 CRC」，再加入新的一段資料，回傳新的 CRC。第一次呼叫傳 `0`。它和 `New` 的效果相同，但不需要建立物件，適合把 CRC 存成結構體欄位、邊收封包邊累加的情況。

簽名：

```go
func Update(crc uint32, tab *Table, p []byte) uint32
```

範例：

```go
package main

import (
	"fmt"
	"hash/crc32"
)

func main() {
	chunks := [][]byte{[]byte("hello"), []byte(", "), []byte("gopher")}

	var crc uint32
	for _, c := range chunks {
		crc = crc32.Update(crc, crc32.IEEETable, c)
		fmt.Printf("after %-8q 0x%08x\n", c, crc)
	}

	fmt.Println("same as whole:", crc == crc32.ChecksumIEEE([]byte("hello, gopher")))
}
```

輸出：

```text
after "hello"  0x3610a686
after ", "     0x11ea5699
after "gopher" 0x1d37ded0
same as whole: true
```

### Size 與 Sum 位元組格式

`crc32.Size` 是常數 `4`，代表 CRC32 佔 4 個位元組。`Sum(nil)` 回傳的位元組是大端序（big-endian，高位在前），和 `Sum32()` 的十六進位寫法一致；寫進檔案格式時可以用 [encoding/binary](/pkg-encoding-binary) 自行決定位元組順序。

下面示範在資料後面附上 CRC，讀取時再驗證，模擬偵測損毀。

簽名：

```go
const Size = 4
```

範例：

```go
package main

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

func pack(payload []byte) []byte {
	return binary.BigEndian.AppendUint32(payload, crc32.ChecksumIEEE(payload))
}

func verify(frame []byte) bool {
	if len(frame) < crc32.Size {
		return false
	}
	payload := frame[:len(frame)-crc32.Size]
	want := binary.BigEndian.Uint32(frame[len(frame)-crc32.Size:])
	return crc32.ChecksumIEEE(payload) == want
}

func main() {
	h := crc32.NewIEEE()
	h.Write([]byte("gopher"))
	fmt.Printf("Size=%d Sum=%x Sum32=%08x\n", crc32.Size, h.Sum(nil), h.Sum32())

	frame := pack([]byte("gopher"))
	fmt.Printf("frame=% x\n", frame)
	fmt.Println("ok:", verify(frame))

	frame[1] ^= 0x01
	fmt.Println("after corruption:", verify(frame))
}
```

輸出：

```text
Size=4 Sum=342bcb2b Sum32=342bcb2b
frame=67 6f 70 68 65 72 34 2b cb 2b
ok: true
after corruption: false
```

## 重點整理

- CRC32 用來偵測意外損毀，不能防惡意竄改
- 記憶體內的資料用 `ChecksumIEEE`；大檔案用 `NewIEEE` 搭配 `io.Copy`
- 非 IEEE 多項式先 `MakeTable` 建表，建一次重複使用
- `Update(crc, tab, p)` 可以不建物件、分段累加
- 不同多項式的結果不通用，讀寫雙方必須約定同一種

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：hash/crc32](https://pkg.go.dev/hash/crc32)
- [Go 1.26.0 原始碼：src/hash/crc32](https://github.com/golang/go/tree/go1.26.0/src/hash/crc32)
