# x/crypto

`golang.org/x/crypto` 提供標準庫 `crypto` 沒有收錄的演算法與協定，本頁介紹密碼雜湊（bcrypt、argon2）、ChaCha20-Poly1305 加密與 SSH 用戶端。

- Module：`golang.org/x/crypto`
- 本書使用版本：v0.59.0（需要 Go 1.26 以上）

## 這個庫做什麼

標準庫已經有 AES、SHA-256、TLS 等常用密碼學工具（見 [`crypto`](/pkg-crypto)），但有些常見需求不在其中：

| 子套件 | 用途 | 為什麼不用標準庫 |
| --- | --- | --- |
| `bcrypt` | 儲存使用者密碼 | 標準庫沒有專門的密碼雜湊 |
| `argon2` | 儲存使用者密碼、從密碼衍生金鑰 | 同上，argon2id 是目前推薦的演算法 |
| `chacha20poly1305` | 對稱式認證加密 | 沒有 AES 硬體加速的裝置上比 AES-GCM 快 |
| `ssh` | SSH 用戶端與伺服器 | 標準庫沒有 SSH |

先分清楚兩件事：**雜湊密碼**是單向的，只能比對、不能還原，用來存登入密碼；**加密**是雙向的，有金鑰就能解回原文，用來保護要再讀出來的資料。一般的 SHA-256 太快，攻擊者每秒能猜數十億次，不適合存密碼；bcrypt 與 argon2 是刻意設計得很慢的雜湊。

## 安裝

```bash
go get golang.org/x/crypto@v0.59.0
```

本頁範例需要金鑰或鹽（salt）時都用 `crypto/rand` 產生，每次執行都不同，所以輸出只印長度、驗證結果等不受影響的內容。`crypto/rand.Read` 保證填滿且不會回傳錯誤（見 [`crypto/rand`](/pkg-crypto-rand)），範例因此省略錯誤檢查。

## bcrypt：最常見的密碼雜湊

### GenerateFromPassword 與 CompareHashAndPassword

`bcrypt` 把密碼轉成 60 字元的字串，裡面已經包含演算法版本、成本（cost）與隨機鹽，存進資料庫時只要一個欄位。

- `GenerateFromPassword(password, cost)`：產生雜湊。cost 每加 1，計算時間約加倍；`bcrypt.DefaultCost` 是 10
- `CompareHashAndPassword(hash, password)`：比對，相符回傳 nil
- `Cost(hash)`：讀出雜湊使用的 cost，可用來判斷舊資料是否需要升級

簽名：

```go
func GenerateFromPassword(password []byte, cost int) ([]byte, error)
func CompareHashAndPassword(hashedPassword, password []byte) error
func Cost(hashedPassword []byte) (int, error)
```

範例：

```go
package main

import (
	"errors"
	"fmt"
	"strings"

	"golang.org/x/crypto/bcrypt"
)

func main() {
	password := []byte("correct horse battery staple")

	hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		fmt.Println("hash:", err)
		return
	}
	fmt.Println("length:", len(hash))
	fmt.Println("prefix:", string(hash[:7]))

	cost, _ := bcrypt.Cost(hash)
	fmt.Println("cost:", cost)

	fmt.Println("correct password:", bcrypt.CompareHashAndPassword(hash, password) == nil)

	err = bcrypt.CompareHashAndPassword(hash, []byte("wrong"))
	fmt.Println("wrong password:", errors.Is(err, bcrypt.ErrMismatchedHashAndPassword))

	again, _ := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	fmt.Println("same hash twice:", string(hash) == string(again))

	_, err = bcrypt.GenerateFromPassword([]byte(strings.Repeat("a", 73)), bcrypt.DefaultCost)
	fmt.Println("73 bytes:", err)
}
```

輸出：

```text
length: 60
prefix: $2a$10$
cost: 10
correct password: true
wrong password: true
same hash twice: false
73 bytes: bcrypt: password length exceeds 72 bytes
```

同一個密碼雜湊兩次結果不同，因為每次的鹽都是隨機的，所以**不能**用「再雜湊一次後比較字串」的方式驗證，一律用 `CompareHashAndPassword`。

注意：bcrypt 只看密碼的前 72 個位元組，超過時 `GenerateFromPassword` 回傳 `ErrPasswordTooLong`。中文一字佔 3 個位元組，長密碼可能比想像中更快碰到上限；需要更長的輸入時改用 argon2。

## argon2：推薦的新選擇

### IDKey

Argon2 是密碼雜湊競賽的優勝者，`argon2.IDKey` 實作其中的 argon2id 變體，同時抵抗 GPU 暴力破解與旁通道攻擊，是新專案的建議選擇。它除了耗時，還會佔用大量記憶體，讓攻擊者難以大量平行猜測。

簽名：

```go
func IDKey(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte
```

| 參數 | 意思 |
| --- | --- |
| `time` | 走訪記憶體的次數 |
| `memory` | 記憶體用量，單位 KiB（`64*1024` 是 64 MiB） |
| `threads` | 平行執行緒數 |
| `keyLen` | 輸出位元組數 |

官方文件引用 RFC 9106 的兩組建議：記憶體充足時 `time=1, memory=2*1024*1024`（約 2 GiB）；記憶體較少時 `time=3, memory=64*1024`，兩者都是 `threads=4`。

和 bcrypt 不同，`IDKey` 只回傳原始位元組，鹽與參數要自己保存。常見做法是編成 `$argon2id$v=19$m=...,t=...,p=...$鹽$雜湊` 格式的字串。範例第一行用固定的鹽，所以結果可重現；後面示範實際儲存與驗證的流程。

範例：

```go
package main

import (
	"crypto/rand"
	"crypto/subtle"
	"encoding/base64"
	"fmt"
	"strings"

	"golang.org/x/crypto/argon2"
)

const (
	argonTime    = 3
	argonMemory  = 64 * 1024
	argonThreads = 4
	argonKeyLen  = 32
)

func hashPassword(password string) string {
	salt := make([]byte, 16)
	rand.Read(salt)
	key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
	return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version, argonMemory, argonTime, argonThreads,
		base64.RawStdEncoding.EncodeToString(salt),
		base64.RawStdEncoding.EncodeToString(key))
}

func verify(encoded, password string) bool {
	parts := strings.Split(encoded, "$")
	if len(parts) != 6 {
		return false
	}
	salt, err := base64.RawStdEncoding.DecodeString(parts[4])
	if err != nil {
		return false
	}
	want, err := base64.RawStdEncoding.DecodeString(parts[5])
	if err != nil {
		return false
	}
	got := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, uint32(len(want)))
	return subtle.ConstantTimeCompare(got, want) == 1
}

func main() {
	fixed := argon2.IDKey([]byte("password"), []byte("fixed-salt-16byt"), 1, 64*1024, 4, 16)
	fmt.Printf("fixed salt key: %x\n", fixed)

	encoded := hashPassword("s3cret")
	fmt.Println("prefix:", strings.Join(strings.Split(encoded, "$")[:4], "$"))
	fmt.Println("verify s3cret:", verify(encoded, "s3cret"))
	fmt.Println("verify guess:", verify(encoded, "guess"))
}
```

輸出：

```text
fixed salt key: 95eeb46afae29640eb1c79928a204f1b
prefix: $argon2id$v=19$m=65536,t=3,p=4
verify s3cret: true
verify guess: false
```

注意：比較雜湊要用 `crypto/subtle.ConstantTimeCompare`，不要用 `bytes.Equal`；後者遇到第一個不同的位元組就返回，攻擊者可以從回應時間推測內容。鹽每個密碼都要用 `crypto/rand` 另外產生，至少 16 個位元組。

## chacha20poly1305：認證加密

### New、Seal 與 Open

ChaCha20-Poly1305 是一種 AEAD（Authenticated Encryption with Associated Data，附帶認證的加密）：加密的同時產生驗證標籤，解密時若密文被改過一個位元就會失敗。它實作標準庫的 `cipher.AEAD` 介面，用法和 [AES-GCM](/pkg-crypto-cipher) 相同。

- 金鑰：32 個位元組（`chacha20poly1305.KeySize`）
- nonce：12 個位元組，同一把金鑰**絕對不能重複使用同一個 nonce**
- 附加資料（additional data）：不加密但受保護的資料，例如訊息編號；解密時必須提供相同內容

簽名：

```go
func New(key []byte) (cipher.AEAD, error)
Seal(dst, nonce, plaintext, additionalData []byte) []byte
Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
```

範例：

```go
package main

import (
	"crypto/rand"
	"fmt"

	"golang.org/x/crypto/chacha20poly1305"
)

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

	aead, err := chacha20poly1305.New(key)
	if err != nil {
		fmt.Println("new:", err)
		return
	}

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

	plaintext := []byte("轉帳 1000 元給 Bob")
	header := []byte("msg-id:42")
	ciphertext := aead.Seal(nil, nonce, plaintext, header)
	fmt.Println("nonce size:", aead.NonceSize(), "overhead:", aead.Overhead())
	fmt.Println("plaintext:", len(plaintext), "ciphertext:", len(ciphertext))

	opened, err := aead.Open(nil, nonce, ciphertext, header)
	fmt.Println("open:", string(opened), err)

	ciphertext[0] ^= 1
	_, err = aead.Open(nil, nonce, ciphertext, header)
	fmt.Println("tampered:", err)

	ciphertext[0] ^= 1
	_, err = aead.Open(nil, nonce, ciphertext, []byte("msg-id:43"))
	fmt.Println("wrong header:", err)
}
```

輸出：

```text
nonce size: 12 overhead: 16
plaintext: 22 ciphertext: 38
open: 轉帳 1000 元給 Bob <nil>
tampered: chacha20poly1305: message authentication failed
wrong header: chacha20poly1305: message authentication failed
```

密文比明文多 16 個位元組，那就是驗證標籤（`Overhead()`）。不論是密文被改、還是附加資料不符，`Open` 都回傳同一個錯誤，不會透露是哪裡出錯。

### NewX：用隨機 nonce 的 XChaCha20-Poly1305

12 位元組的 nonce 用隨機產生，加密次數一多就有重複的風險。`NewX` 建立 XChaCha20-Poly1305，nonce 加長到 24 個位元組，隨機產生也不必擔心碰撞，是最省心的寫法。慣例是把 nonce 放在密文前面一起存。

簽名：

```go
func NewX(key []byte) (cipher.AEAD, error)
```

範例：

```go
package main

import (
	"crypto/rand"
	"fmt"

	"golang.org/x/crypto/chacha20poly1305"
)

func encrypt(key, plaintext []byte) ([]byte, error) {
	aead, err := chacha20poly1305.NewX(key)
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(plaintext)+aead.Overhead())
	rand.Read(nonce)
	return aead.Seal(nonce, nonce, plaintext, nil), nil
}

func decrypt(key, message []byte) ([]byte, error) {
	aead, err := chacha20poly1305.NewX(key)
	if err != nil {
		return nil, err
	}
	if len(message) < aead.NonceSize() {
		return nil, fmt.Errorf("message too short")
	}
	nonce, ciphertext := message[:aead.NonceSize()], message[aead.NonceSize():]
	return aead.Open(nil, nonce, ciphertext, nil)
}

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

	msg, err := encrypt(key, []byte("hello"))
	if err != nil {
		fmt.Println("encrypt:", err)
		return
	}
	fmt.Println("nonce size:", chacha20poly1305.NonceSizeX, "message length:", len(msg))

	plain, err := decrypt(key, msg)
	fmt.Println("decrypt:", string(plain), err)

	_, err = chacha20poly1305.NewX([]byte("short key"))
	fmt.Println("bad key:", err)
}
```

輸出：

```text
nonce size: 24 message length: 45
decrypt: hello <nil>
bad key: chacha20poly1305: bad key length
```

訊息長度 45 = nonce 24 + 明文 5 + 標籤 16。`Seal` 的第一個參數 `dst` 傳入 nonce，結果就會接在 nonce 後面，不必另外複製。

注意：金鑰長度不是 32 位元組時 `New`、`NewX` 回傳錯誤。不要把密碼字串直接當金鑰，要先用 `argon2.IDKey` 衍生出 32 位元組。

## ssh：SSH 用戶端

### Dial、NewSession 與 Output

`ssh` 套件可以寫出連到遠端主機、執行指令的程式，例如部署工具。流程是：

1. 準備 `ssh.ClientConfig`：使用者、認證方式、主機金鑰驗證
2. `ssh.Dial` 建立連線，得到 `*ssh.Client`
3. `client.NewSession()` 開一個工作階段（session），一個 session 只能執行一個指令
4. `session.Output(cmd)` 執行並取得標準輸出

認證方式常用 `ssh.PublicKeys(signer)`（金鑰）或 `ssh.Password(...)`（密碼）。實際讀取私鑰檔的寫法是 `ssh.ParsePrivateKey(pemBytes)` 取得 `Signer`。

簽名：

```go
func Dial(network, addr string, config *ClientConfig) (*Client, error)
func (c *Client) NewSession() (*Session, error)
func (s *Session) Output(cmd string) ([]byte, error)
func PublicKeys(signers ...Signer) AuthMethod
func FixedHostKey(key PublicKey) HostKeyCallback
```

為了讓範例不依賴外部主機，`startTestServer` 用同一個套件在本機起一個只會回覆指令字串的迷你 SSH 伺服器；連真實主機時只需要 `main` 裡的用戶端部分，把位址換成 `"host:22"`。

範例：

```go
package main

import (
	"bytes"
	"crypto/ed25519"
	"crypto/rand"
	"encoding/binary"
	"fmt"
	"net"
	"time"

	"golang.org/x/crypto/ssh"
)

func startTestServer(authorized ssh.PublicKey) (addr string, hostKey ssh.PublicKey, err error) {
	_, hostPriv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		return "", nil, err
	}
	hostSigner, err := ssh.NewSignerFromKey(hostPriv)
	if err != nil {
		return "", nil, err
	}

	config := &ssh.ServerConfig{
		PublicKeyCallback: func(meta ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
			if meta.User() == "gopher" && bytes.Equal(key.Marshal(), authorized.Marshal()) {
				return nil, nil
			}
			return nil, fmt.Errorf("unknown key for %s", meta.User())
		},
	}
	config.AddHostKey(hostSigner)

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return "", nil, err
	}
	go func() {
		for {
			conn, err := ln.Accept()
			if err != nil {
				return
			}
			go serveConn(conn, config)
		}
	}()
	return ln.Addr().String(), hostSigner.PublicKey(), nil
}

func serveConn(conn net.Conn, config *ssh.ServerConfig) {
	_, chans, reqs, err := ssh.NewServerConn(conn, config)
	if err != nil {
		return
	}
	go ssh.DiscardRequests(reqs)
	for newCh := range chans {
		if newCh.ChannelType() != "session" {
			newCh.Reject(ssh.UnknownChannelType, "only session")
			continue
		}
		ch, requests, err := newCh.Accept()
		if err != nil {
			continue
		}
		go func() {
			defer ch.Close()
			for req := range requests {
				if req.Type != "exec" || len(req.Payload) < 4 {
					req.Reply(false, nil)
					continue
				}
				cmd := string(req.Payload[4:])
				req.Reply(true, nil)
				fmt.Fprintf(ch, "you ran %q\n", cmd)
				status := make([]byte, 4)
				binary.BigEndian.PutUint32(status, 0)
				ch.SendRequest("exit-status", false, status)
				return
			}
		}()
	}
}

func main() {
	_, clientPriv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		fmt.Println("keygen:", err)
		return
	}
	clientSigner, err := ssh.NewSignerFromKey(clientPriv)
	if err != nil {
		fmt.Println("signer:", err)
		return
	}

	addr, hostKey, err := startTestServer(clientSigner.PublicKey())
	if err != nil {
		fmt.Println("server:", err)
		return
	}

	config := &ssh.ClientConfig{
		User:            "gopher",
		Auth:            []ssh.AuthMethod{ssh.PublicKeys(clientSigner)},
		HostKeyCallback: ssh.FixedHostKey(hostKey),
		Timeout:         5 * time.Second,
	}
	client, err := ssh.Dial("tcp", addr, config)
	if err != nil {
		fmt.Println("dial:", err)
		return
	}
	defer client.Close()

	session, err := client.NewSession()
	if err != nil {
		fmt.Println("session:", err)
		return
	}
	defer session.Close()

	out, err := session.Output("uname -s")
	fmt.Printf("output: %serr: %v\n", out, err)

	config.User = "intruder"
	_, err = ssh.Dial("tcp", addr, config)
	fmt.Println("wrong user:", err)
}
```

輸出：

```text
output: you ran "uname -s"
err: <nil>
wrong user: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain
```

注意：`HostKeyCallback` 是必填欄位，用來確認連到的真的是你的主機，防止中間人攻擊。`ssh.InsecureIgnoreHostKey()` 會接受任何主機金鑰，官方文件註明不應用於正式環境；正式程式請用下一節的 `knownhosts`。

### knownhosts：驗證主機金鑰

`golang.org/x/crypto/ssh/knownhosts` 讀取 OpenSSH 格式的 `known_hosts` 檔，產生可以直接放進 `ClientConfig.HostKeyCallback` 的函式。實務上路徑通常是 `~/.ssh/known_hosts`。

簽名：

```go
func New(files ...string) (ssh.HostKeyCallback, error)
func Line(addresses []string, key ssh.PublicKey) string
```

驗證失敗時回傳 `*knownhosts.KeyError`：`Want` 不為空表示主機金鑰**變了**（可能是攻擊，也可能是主機重灌）；`Want` 為空表示這台主機還沒登錄過。

範例：

```go
package main

import (
	"crypto/ed25519"
	"crypto/rand"
	"errors"
	"fmt"
	"net"
	"os"
	"path/filepath"

	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/knownhosts"
)

func newHostKey() ssh.PublicKey {
	pub, _, _ := ed25519.GenerateKey(rand.Reader)
	key, _ := ssh.NewPublicKey(pub)
	return key
}

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

	trusted := newHostKey()
	path := filepath.Join(dir, "known_hosts")
	line := knownhosts.Line([]string{"git.example.com"}, trusted) + "\n"
	if err := os.WriteFile(path, []byte(line), 0o600); err != nil {
		fmt.Println("write:", err)
		return
	}

	callback, err := knownhosts.New(path)
	if err != nil {
		fmt.Println("knownhosts:", err)
		return
	}

	remote := &net.TCPAddr{IP: net.IPv4(192, 0, 2, 10), Port: 22}
	fmt.Println("trusted key:", callback("git.example.com:22", remote, trusted))

	err = callback("git.example.com:22", remote, newHostKey())
	var keyErr *knownhosts.KeyError
	if errors.As(err, &keyErr) {
		fmt.Println("changed key: mismatch, known entries =", len(keyErr.Want))
	}

	err = callback("new.example.com:22", remote, newHostKey())
	if errors.As(err, &keyErr) {
		fmt.Println("unknown host: known entries =", len(keyErr.Want))
	}
}
```

輸出：

```text
trusted key: <nil>
changed key: mismatch, known entries = 1
unknown host: known entries = 0
```

範例把檔案建在 `os.MkdirTemp` 的暫存目錄並在結束時刪除。

## 不要使用的子套件

下列子套件或 API 在 v0.59.0 原始碼中標記為 `Deprecated`，新程式不要使用：

| 子套件／API | 原因與替代 |
| --- | --- |
| `blowfish`、`cast5`、`tea`、`xtea` | 老舊分組密碼，改用標準庫 `crypto/aes`（搭配 `crypto/cipher` 的 GCM）或 `chacha20poly1305` |
| `twofish` | 舊式密碼，改用 `crypto/aes` |
| `md4`、`ripemd160` | 雜湊已被破解或過時，改用 `crypto/sha256`、`crypto/sha3` |
| `bn256` | 安全強度已降低 |
| `poly1305` | 低階 MAC，容易誤用，改用 `chacha20poly1305` |
| `salsa20/salsa` | 暴露不安全的低階運算，改用 `chacha20poly1305` |
| `curve25519.ScalarMult` | 改用 `curve25519.X25519` 或標準庫 `crypto/ecdh` |
| `ssh/terminal` | 已搬到 `golang.org/x/term` |
| `ssh/test` | 僅供內部測試 |
| `ssh` 的 DSA 金鑰與憑證演算法常數 | 不再支援 DSA |
| `acme` 中 RFC 8555 之前的舊版 API | 改用 `CreateCertFromOrder` 等新流程 |

另外有幾個子套件沒有標記 Deprecated，但說明中寫明只是標準庫的包裝且已凍結（frozen，不再加新功能）：`ed25519`、`sha3`、`hkdf`、`pbkdf2`、`curve25519`。新程式直接用標準庫的 [`crypto/ed25519`](/pkg-crypto-ed25519)、[`crypto/sha3`](/pkg-crypto-sha3)、[`crypto/hkdf`](/pkg-crypto-hkdf)、`crypto/pbkdf2`、[`crypto/ecdh`](/pkg-crypto-ecdh) 即可。

## 重點整理

- 存使用者密碼用 bcrypt 或 argon2id，不要用 SHA-256；驗證 bcrypt 一律用 `CompareHashAndPassword`
- bcrypt 只看前 72 個位元組；argon2 要自己保存鹽與參數，比對用 `subtle.ConstantTimeCompare`
- `chacha20poly1305` 是 AEAD：同一把金鑰不可重複 nonce，想隨機產生 nonce 就用 `NewX`
- SSH 用戶端要設定 `HostKeyCallback`，正式環境用 `knownhosts`，不要用 `InsecureIgnoreHostKey`
- 依原始碼的 `Deprecated` 標記避開舊演算法；已有標準庫版本的子套件直接用標準庫

## 資料來源

- [pkg.go.dev：golang.org/x/crypto](https://pkg.go.dev/golang.org/x/crypto)
