# crypto/cipher

`crypto/cipher` 提供區塊加密器的加密模式，最重要的是 AEAD（GCM）：一次完成加密與竄改偵測。

## 這個套件做什麼

[crypto/aes](/pkg-crypto-aes) 給你的是只能處理 16 bytes 的區塊加密器（`cipher.Block`）。`crypto/cipher` 把它包裝成能加密任意長度資料的「模式」。

模式分兩類：

| 類型 | 例子 | 能偵測竄改？ | 建議 |
| --- | --- | --- | --- |
| AEAD（認證加密） | GCM | 能 | 新程式一律用這個 |
| 只加密 | CBC、CTR | 不能 | 只在對接既有格式時使用，且必須另外加上 HMAC |

為什麼一定要偵測竄改？只加密的模式下，攻擊者即使看不懂密文，也能改動密文中的位元，讓解密結果跟著被改（例如把金額改掉），甚至藉此推出明文。AEAD（Authenticated Encryption with Associated Data，附帶資料的認證加密）在密文後附上一個驗證標籤（tag），解密時先檢查標籤，任何一個位元被改都會解密失敗。

`crypto/cipher` 的 CFB、OFB 模式已標記棄用（同樣因為無法偵測竄改），不要使用，見 [/deprecations](/deprecations)。

GCM 的三個關鍵名詞：

| 名詞 | 意思 |
| --- | --- |
| nonce | 每次加密用的一次性數字（number used once）。同一把金鑰下**絕對不能重複**，否則安全性完全瓦解。不需要保密，可以和密文一起存放 |
| tag | 驗證標籤，16 bytes，附在密文後面 |
| additional data（AAD） | 不加密、但受保護的附帶資料，例如資料所屬的使用者 ID；解密時必須提供同樣的值 |

## 匯入

```go
import "crypto/cipher"
```

通常會同時匯入 `"crypto/aes"` 與 `"crypto/rand"`。

## 常用 API

### cipher.NewGCM 與 AEAD 介面

`NewGCM` 把 AES 區塊加密器包成 `AEAD` 介面。`AEAD` 只有四個方法：

| 方法 | 作用 |
| --- | --- |
| `NonceSize()` | nonce 要幾個 bytes（GCM 是 12） |
| `Overhead()` | 密文比明文多幾個 bytes（GCM 的 tag 是 16） |
| `Seal(dst, nonce, plaintext, additionalData)` | 加密並附上 tag，結果附加在 `dst` 後面 |
| `Open(dst, nonce, ciphertext, additionalData)` | 驗證 tag 並解密；驗證失敗回傳錯誤 |

使用 `NewGCM` 時，nonce 由你自己產生與保存。每次執行金鑰與 nonce 都不同，範例只印長度與解密結果。

注意：傳給 `Seal` 的 nonce 長度不是 `NonceSize()` 時會 panic。

簽名：

```go
func NewGCM(cipher Block) (AEAD, error)

type AEAD interface {
	NonceSize() int
	Overhead() int
	Seal(dst, nonce, plaintext, additionalData []byte) []byte
	Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
}
```

範例：

```go
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
)

func main() {
	key := make([]byte, 32)
	rand.Read(key)

	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("建立失敗:", err)
		return
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		fmt.Println("建立 GCM 失敗:", err)
		return
	}

	nonce := make([]byte, gcm.NonceSize())
	rand.Read(nonce)

	plaintext := []byte("hello, gcm")
	ciphertext := gcm.Seal(nil, nonce, plaintext, nil)

	decrypted, err := gcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		fmt.Println("解密失敗:", err)
		return
	}

	fmt.Println("NonceSize:", gcm.NonceSize())
	fmt.Println("Overhead:", gcm.Overhead())
	fmt.Println("明文長度:", len(plaintext), "密文長度:", len(ciphertext))
	fmt.Println("解密結果:", string(decrypted))
}
```

輸出：

```text
NonceSize: 12
Overhead: 16
明文長度: 10 密文長度: 26
解密結果: hello, gcm
```

### 把 nonce 存在密文前面

nonce 不需要保密，但解密時一定要有。最常見的做法：加密時把 nonce 放在輸出最前面，解密時先切出前 `NonceSize()` 個 bytes 當 nonce。

技巧：`gcm.Seal(nonce, nonce, plaintext, nil)` 的第一個參數 `dst` 傳 `nonce`，加密結果就會直接附加在 nonce 後面，一行完成「nonce + 密文 + tag」。

因為每次 nonce 都是隨機的，同一段明文加密兩次會得到不同結果，攻擊者無法從密文看出「這兩筆資料內容相同」。

解密前要先檢查長度，否則資料太短時切片會 panic。

範例：

```go
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"errors"
	"fmt"
)

func encrypt(gcm cipher.AEAD, plaintext []byte) []byte {
	nonce := make([]byte, gcm.NonceSize())
	rand.Read(nonce)
	return gcm.Seal(nonce, nonce, plaintext, nil)
}

func decrypt(gcm cipher.AEAD, data []byte) ([]byte, error) {
	n := gcm.NonceSize()
	if len(data) < n {
		return nil, errors.New("[Invalid] ciphertext: too short")
	}
	nonce, ciphertext := data[:n], data[n:]
	return gcm.Open(nil, nonce, ciphertext, nil)
}

func main() {
	key := make([]byte, 32)
	rand.Read(key)
	block, _ := aes.NewCipher(key)
	gcm, _ := cipher.NewGCM(block)

	a := encrypt(gcm, []byte("同一段文字"))
	b := encrypt(gcm, []byte("同一段文字"))
	fmt.Println("兩次密文相同:", string(a) == string(b))
	fmt.Println("輸出長度:", len(a))

	plain, err := decrypt(gcm, a)
	fmt.Println("解密:", string(plain), err)

	_, err = decrypt(gcm, []byte("abc"))
	fmt.Println("太短:", err)
}
```

輸出：

```text
兩次密文相同: false
輸出長度: 43
解密: 同一段文字 <nil>
太短: [Invalid] ciphertext: too short
```

「同一段文字」是 15 bytes（每個中文字 3 bytes），加上 nonce 12 與 tag 16，共 43 bytes。

### cipher.NewGCMWithRandomNonce

`NewGCMWithRandomNonce`（Go 1.24 起）把上一節的 nonce 處理自動化：`Seal` 自己產生 96 位元隨機 nonce 並放在密文前面，`Open` 自己切出來。所以 `NonceSize()` 是 0，`nonce` 參數傳 `nil`；`Overhead()` 是 28（nonce 12 + tag 16）。新程式建議優先使用它，避免自己處理 nonce 出錯。

注意：底層必須是 `aes.NewCipher` 建立的 Block。同一把金鑰加密的訊息數不可超過 2^32 則，超過就要換金鑰，以免隨機 nonce 撞號。

簽名：

```go
func NewGCMWithRandomNonce(cipher Block) (AEAD, error)
```

範例：

```go
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
)

func main() {
	key := make([]byte, 32)
	rand.Read(key)
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("建立失敗:", err)
		return
	}
	gcm, err := cipher.NewGCMWithRandomNonce(block)
	if err != nil {
		fmt.Println("建立 GCM 失敗:", err)
		return
	}

	fmt.Println("NonceSize:", gcm.NonceSize())
	fmt.Println("Overhead:", gcm.Overhead())

	sealed := gcm.Seal(nil, nil, []byte("hello"), nil)
	fmt.Println("密文長度:", len(sealed))

	plain, err := gcm.Open(nil, nil, sealed, nil)
	fmt.Println("解密:", string(plain), err)
}
```

輸出：

```text
NonceSize: 0
Overhead: 28
密文長度: 33
解密: hello <nil>
```

### 附加資料（additional data）

`Seal`／`Open` 的最後一個參數是附加資料：它不會被加密，也不會存進密文，但會被 tag 保護。解密時必須提供完全相同的值，否則失敗。

用途：把密文「綁定」到它的情境。例如資料庫裡 A 使用者的加密病歷，以使用者 ID 當附加資料；就算有人把這筆密文搬到 B 使用者的欄位，用 B 的 ID 解密也會失敗。

範例：

```go
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
)

func main() {
	key := make([]byte, 32)
	rand.Read(key)
	block, _ := aes.NewCipher(key)
	gcm, _ := cipher.NewGCMWithRandomNonce(block)

	userA := []byte("user:1001")
	userB := []byte("user:2002")

	sealed := gcm.Seal(nil, nil, []byte("A 的病歷"), userA)

	plain, err := gcm.Open(nil, nil, sealed, userA)
	fmt.Println("正確 AAD:", string(plain), err)

	_, err = gcm.Open(nil, nil, sealed, userB)
	fmt.Println("錯誤 AAD:", err)
}
```

輸出：

```text
正確 AAD: A 的病歷 <nil>
錯誤 AAD: cipher: message authentication failed
```

### 竄改偵測：Open 的錯誤

`Open` 回傳錯誤只有一種意思：資料不可信。可能是密文被改過、金鑰不對、nonce 或附加資料不符。錯誤訊息刻意不說明是哪一種，以免洩漏資訊給攻擊者。

收到錯誤時，丟棄整筆資料，不要使用 `Open` 回傳的任何內容。

範例：

```go
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
)

func main() {
	key := make([]byte, 32)
	rand.Read(key)
	block, _ := aes.NewCipher(key)
	gcm, _ := cipher.NewGCMWithRandomNonce(block)

	sealed := gcm.Seal(nil, nil, []byte("金額: 100"), nil)

	tampered := append([]byte(nil), sealed...)
	tampered[len(tampered)-1] ^= 0x01

	_, err := gcm.Open(nil, nil, tampered, nil)
	fmt.Println("竄改後:", err)

	otherKey := make([]byte, 32)
	rand.Read(otherKey)
	otherBlock, _ := aes.NewCipher(otherKey)
	otherGCM, _ := cipher.NewGCMWithRandomNonce(otherBlock)
	_, err = otherGCM.Open(nil, nil, sealed, nil)
	fmt.Println("錯誤金鑰:", err)
}
```

輸出：

```text
竄改後: cipher: message authentication failed
錯誤金鑰: cipher: message authentication failed
```

`^= 0x01` 只翻轉最後一個 byte 的一個位元，就足以讓驗證失敗。

### cipher.Block 介面

`Block` 是所有區塊加密器的共同介面，`aes.NewCipher` 回傳的就是它。GCM 等模式只依賴這個介面。

範例用全零金鑰與全零 nonce 加密 16 個零 bytes，這是 GCM 規格的公開測試案例，結果固定，前 16 bytes 是密文、後 16 bytes 是 tag。這只是為了讓輸出可重現；實務上 nonce 絕不能固定，否則同一把金鑰第二次加密就會洩漏資訊。

簽名：

```go
type Block interface {
	BlockSize() int
	Encrypt(dst, src []byte)
	Decrypt(dst, src []byte)
}
```

範例：

```go
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
)

func main() {
	key := make([]byte, 16)
	nonce := make([]byte, 12)

	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("建立失敗:", err)
		return
	}
	var b cipher.Block = block
	fmt.Println("BlockSize:", b.BlockSize())

	gcm, err := cipher.NewGCM(b)
	if err != nil {
		fmt.Println("建立 GCM 失敗:", err)
		return
	}
	out := gcm.Seal(nil, nonce, make([]byte, 16), nil)
	fmt.Println(hex.EncodeToString(out))
}
```

輸出：

```text
BlockSize: 16
0388dace60b6a392f328c2b971b2fe78ab6e47d42cec13bdf53a67b21257bddf
```

## 重點整理

- 加密資料用 AEAD（GCM），它同時加密並偵測竄改；CFB、OFB 已棄用，CBC、CTR 只用於對接舊格式
- 新程式優先用 `cipher.NewGCMWithRandomNonce`（Go 1.24 起），nonce 自動產生並放在密文前面
- 用 `cipher.NewGCM` 時，nonce 每次用 [crypto/rand](/pkg-crypto-rand) 產生、同一金鑰下絕不重複，常見做法是 `Seal(nonce, nonce, ...)` 存在密文前面
- 附加資料把密文綁定到情境（如使用者 ID），解密時必須相同
- `Open` 回傳錯誤就丟棄整筆資料；錯誤不區分是竄改、金鑰錯或 AAD 不符

## 資料來源

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