# crypto/aes

`crypto/aes` 提供 AES 區塊加密演算法，是 Go 對稱加密的核心元件，通常搭配 [crypto/cipher](/pkg-crypto-cipher) 的 GCM 使用。

## 這個套件做什麼

AES（Advanced Encryption Standard）是目前最普遍的對稱加密（symmetric encryption）演算法：加密和解密用**同一把金鑰**。HTTPS、磁碟加密、資料庫欄位加密幾乎都用它。

AES 本身是「區塊加密器」（block cipher）：一次只能加密固定 16 bytes 的資料。真實資料長短不一，所以實務上一定要搭配「加密模式」，把區塊加密器擴展成能處理任意長度、還能偵測竄改的方案。這些模式在 [crypto/cipher](/pkg-crypto-cipher)。

| 套件 | 角色 | 比喻 |
| --- | --- | --- |
| `crypto/aes` | 產生區塊加密器 `cipher.Block` | 一台只能鎖 16 bytes 小盒子的機器 |
| `crypto/cipher` | 加密模式（推薦 GCM） | 把機器裝上輸送帶與封條，處理任意長度並防竄改 |

金鑰長度決定 AES 的強度：

| 金鑰長度 | 演算法 |
| --- | --- |
| 16 bytes | AES-128 |
| 24 bytes | AES-192 |
| 32 bytes | AES-256 |

在有硬體 AES 指令的 CPU（現代 x86-64、ARM64）上，Go 的 AES 會使用硬體加速，速度快且以常數時間執行。

## 匯入

```go
import "crypto/aes"
```

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

## 常用 API

### aes.NewCipher

用金鑰建立 AES 區塊加密器，回傳 `cipher.Block` 介面。金鑰長度決定是 AES-128、AES-192 還是 AES-256。不論金鑰多長，區塊大小都是 16 bytes（常數 `aes.BlockSize`）。

範例用全零金鑰只為示範長度；實務金鑰要用 [crypto/rand](/pkg-crypto-rand) 產生。

簽名：

```go
func NewCipher(key []byte) (cipher.Block, error)
```

範例：

```go
package main

import (
	"crypto/aes"
	"fmt"
)

func main() {
	for _, n := range []int{16, 24, 32} {
		block, err := aes.NewCipher(make([]byte, n))
		if err != nil {
			fmt.Println("建立失敗:", err)
			return
		}
		fmt.Printf("金鑰 %d bytes → AES-%d，BlockSize %d\n", n, n*8, block.BlockSize())
	}
}
```

輸出：

```text
金鑰 16 bytes → AES-128，BlockSize 16
金鑰 24 bytes → AES-192，BlockSize 16
金鑰 32 bytes → AES-256，BlockSize 16
```

### aes.KeySizeError

金鑰長度不是 16、24、32 時，`NewCipher` 回傳 `aes.KeySizeError`，它的值就是你傳入的金鑰長度。用 `errors.As` 可以取出這個型別（見[自訂錯誤型別](/errors-custom-types)）。

常見錯誤是把密碼字串直接當金鑰。密碼長度不固定、也不夠隨機，應該用金鑰衍生函式轉換，例如 [x/crypto](/lib-x-crypto) 的 argon2，或對已經夠隨機的秘密使用 [crypto/hkdf](/pkg-crypto-hkdf)。

簽名：

```go
type KeySizeError int

func (k KeySizeError) Error() string
```

範例：

```go
package main

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

func main() {
	_, err := aes.NewCipher([]byte("short-key"))
	fmt.Println("錯誤:", err)

	var ks aes.KeySizeError
	if errors.As(err, &ks) {
		fmt.Println("實際長度:", int(ks))
	}
}
```

輸出：

```text
錯誤: crypto/aes: invalid key size 9
實際長度: 9
```

### Block.Encrypt 與 Block.Decrypt

`cipher.Block` 的 `Encrypt`／`Decrypt` 一次處理剛好一個 16 bytes 區塊。範例使用 FIPS-197 標準文件裡的測試向量（固定金鑰與明文），所以結果可以和標準對照。

注意：不要直接用 `Encrypt` 一塊一塊加密真實資料。相同的明文區塊會得到相同的密文區塊，攻擊者能看出資料規律，也無法偵測竄改。這個 API 是給加密模式內部使用的；實務請用下一節的 GCM。

注意：`src` 或 `dst` 短於 16 bytes 時會 panic。

簽名：

```go
Encrypt(dst, src []byte)
Decrypt(dst, src []byte)
```

範例：

```go
package main

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

func main() {
	key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f")
	plain, _ := hex.DecodeString("00112233445566778899aabbccddeeff")

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

	out := make([]byte, aes.BlockSize)
	block.Encrypt(out, plain)
	fmt.Println("加密:", hex.EncodeToString(out))

	back := make([]byte, aes.BlockSize)
	block.Decrypt(back, out)
	fmt.Println("解密:", hex.EncodeToString(back))
}
```

輸出：

```text
加密: 69c4e0d86a7b0430d8cdb78070b4c55a
解密: 00112233445566778899aabbccddeeff
```

### 搭配 GCM 加密任意資料

正確的 AES 用法：`aes.NewCipher` 建立區塊加密器，交給 `cipher.NewGCMWithRandomNonce`（Go 1.24 起）包成 AEAD，之後用 `Seal` 加密、`Open` 解密。GCM 會自動處理任意長度資料，並在解密時檢查資料有沒有被竄改。

每次執行金鑰與隨機 nonce 都不同，範例只印長度與解密結果。密文長度 = 明文 23 bytes + 隨機 nonce 12 bytes + 驗證標籤 16 bytes = 51 bytes。

GCM 的完整說明（nonce、附加資料、竄改偵測）見 [crypto/cipher](/pkg-crypto-cipher)。

範例：

```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
	}

	sealed := gcm.Seal(nil, nil, []byte("信用卡末四碼 1234"), nil)
	plain, err := gcm.Open(nil, nil, sealed, nil)
	if err != nil {
		fmt.Println("解密失敗:", err)
		return
	}
	fmt.Println("密文長度:", len(sealed))
	fmt.Println("解密結果:", string(plain))
}
```

輸出：

```text
密文長度: 51
解密結果: 信用卡末四碼 1234
```

## 重點整理

- AES 是對稱加密，加解密用同一把金鑰；金鑰 16／24／32 bytes 對應 AES-128／192／256
- `aes.NewCipher` 回傳 `cipher.Block`，金鑰長度錯誤時回傳 `aes.KeySizeError`
- `Block.Encrypt` 一次只處理 16 bytes，不要直接用來加密資料
- 實務用法：`aes.NewCipher` → `cipher.NewGCMWithRandomNonce` 或 `cipher.NewGCM` → `Seal`／`Open`
- 金鑰用 [crypto/rand](/pkg-crypto-rand) 產生，不要直接拿密碼字串當金鑰

## 資料來源

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