# crypto/sha3

`crypto/sha3` 計算 SHA-3 系列雜湊值，以及可自訂輸出長度的 SHAKE 函式（Go 1.24 起納入標準庫）。

## 這個套件做什麼

SHA-3 是美國 NIST 在 FIPS 202 標準化的雜湊演算法家族，內部結構（稱為 Keccak 海綿結構）和 SHA-2（[crypto/sha256](/pkg-crypto-sha256)、`crypto/sha512`）完全不同。兩者目前都安全，SHA-3 的價值在於「設計不同」：萬一未來 SHA-2 出現弱點，SHA-3 不會跟著受影響。

| 需求 | 選擇 |
| --- | --- |
| 一般用途、和其他系統互通 | SHA-256（最普及） |
| 規範或協定明確要求 SHA-3 | `sha3.Sum256` 等 |
| 需要任意長度的輸出 | SHAKE128／SHAKE256 |

SHAKE 是「可延伸輸出函式」（XOF, Extendable Output Function）：一般雜湊的輸出長度固定，SHAKE 則可以要多長就取多長，像從水龍頭接水，要接多少都可以。

Go 1.24 之前 SHA-3 只在 `golang.org/x/crypto/sha3`，Go 1.24 起改進標準庫，見 [/go-1-24](/go-1-24)。

注意：SHA-3 和 SHA-256 一樣算得很快，不適合直接存密碼；密碼請用 [x/crypto](/lib-x-crypto) 的 bcrypt 或 argon2。

## 匯入

```go
import "crypto/sha3"
```

## 常用 API

### sha3.Sum256

一次算出整段資料的 SHA3-256，回傳 `[32]byte` 陣列。注意 SHA3-256 和 SHA-256 是不同演算法，同樣輸入的結果不同。

簽名：

```go
func Sum256(data []byte) [32]byte
```

範例：

```go
package main

import (
	"crypto/sha3"
	"fmt"
)

func main() {
	sum := sha3.Sum256([]byte("hello"))
	fmt.Printf("型別: %T\n", sum)
	fmt.Printf("%x\n", sum)
}
```

輸出：

```text
型別: [32]uint8
3338be694f50c5f338814986cdf0686453a888b84f424d792af4b9202398f392
```

對照 `sha256.Sum256([]byte("hello"))` 是 `2cf24dba...`，兩者完全不同。

### Sum224、Sum384、Sum512

依需要的長度選擇函式，數字是輸出的位元數。輸出越長，抗碰撞能力越強，但多數應用 256 位元已足夠。

簽名：

```go
func Sum224(data []byte) [28]byte
func Sum384(data []byte) [48]byte
func Sum512(data []byte) [64]byte
```

範例：

```go
package main

import (
	"crypto/sha3"
	"fmt"
)

func main() {
	data := []byte("hello")
	a := sha3.Sum224(data)
	b := sha3.Sum256(data)
	c := sha3.Sum384(data)
	d := sha3.Sum512(data)
	fmt.Println("SHA3-224:", len(a), "bytes")
	fmt.Println("SHA3-256:", len(b), "bytes")
	fmt.Println("SHA3-384:", len(c), "bytes")
	fmt.Println("SHA3-512:", len(d), "bytes")
	fmt.Printf("%x\n", d)
}
```

輸出：

```text
SHA3-224: 28 bytes
SHA3-256: 32 bytes
SHA3-384: 48 bytes
SHA3-512: 64 bytes
75d527c368f2efe848ecf6b073a36767800805e9eef2b1857d5f984f036eb6df891d75f72d9b154518c1cd58835286d1da9a38deba3de98b5a53e5ed78a84976
```

### sha3.New256 與 SHA3 型別

資料分批到達時，用 `New224`／`New256`／`New384`／`New512` 建立 `*sha3.SHA3`，持續 `Write`，最後 `Sum(nil)`。`*SHA3` 實作 [hash.Hash](/pkg-hash)，可以當 `io.Copy` 的目的地。

`sha3.SHA3` 的零值就是一個可用的 SHA3-256，宣告 `var h sha3.SHA3` 即可開始寫入。

簽名：

```go
func New256() *SHA3
func (s *SHA3) Write(p []byte) (n int, err error)
func (s *SHA3) Sum(b []byte) []byte
```

範例：

```go
package main

import (
	"crypto/sha3"
	"fmt"
	"io"
	"strings"
)

func main() {
	h := sha3.New256()
	io.Copy(h, strings.NewReader("hel"))
	h.Write([]byte("lo"))
	fmt.Printf("New256 : %x\n", h.Sum(nil))

	var zero sha3.SHA3
	zero.Write([]byte("hello"))
	fmt.Printf("零值    : %x\n", zero.Sum(nil))
	fmt.Println("Size:", zero.Size(), "BlockSize:", zero.BlockSize())
}
```

輸出：

```text
New256 : 3338be694f50c5f338814986cdf0686453a888b84f424d792af4b9202398f392
零值    : 3338be694f50c5f338814986cdf0686453a888b84f424d792af4b9202398f392
Size: 32 BlockSize: 136
```

### sha3.SumSHAKE256 與 SumSHAKE128

一次算出指定長度的 SHAKE 輸出。`length` 是要幾個 bytes。同樣輸入下，較短的輸出就是較長輸出的前綴。

安全強度：SHAKE128 約 128 位元、SHAKE256 約 256 位元（輸出長度也要夠長才達得到）。

簽名：

```go
func SumSHAKE128(data []byte, length int) []byte
func SumSHAKE256(data []byte, length int) []byte
```

範例：

```go
package main

import (
	"crypto/sha3"
	"fmt"
)

func main() {
	fmt.Printf("16 bytes: %x\n", sha3.SumSHAKE256([]byte("hello"), 16))
	fmt.Printf("32 bytes: %x\n", sha3.SumSHAKE256([]byte("hello"), 32))
	fmt.Printf("SHAKE128: %x\n", sha3.SumSHAKE128([]byte("hello"), 16))
}
```

輸出：

```text
16 bytes: 1234075ae4a1e77316cf2d8000974581
32 bytes: 1234075ae4a1e77316cf2d8000974581a343b9ebbca7e3d1db83394c30f22162
SHAKE128: 8eb4b6a932f280335ee1a279f8c208a3
```

### sha3.NewSHAKE128 與 SHAKE 型別

需要分批寫入、或分批讀出輸出時，用 `NewSHAKE128`／`NewSHAKE256` 建立 `*sha3.SHAKE`。先 `Write` 寫入資料，再用 `Read` 一段一段讀出，讀出的內容會接續下去。

注意：開始 `Read` 之後再呼叫 `Write` 會 panic；要重新開始請先 `Reset()`。

簽名：

```go
func NewSHAKE128() *SHAKE
func NewSHAKE256() *SHAKE
func (s *SHAKE) Write(p []byte) (n int, err error)
func (s *SHAKE) Read(p []byte) (n int, err error)
```

範例：

```go
package main

import (
	"crypto/sha3"
	"fmt"
)

func main() {
	x := sha3.NewSHAKE128()
	x.Write([]byte("hello"))

	first := make([]byte, 8)
	second := make([]byte, 8)
	x.Read(first)
	x.Read(second)

	fmt.Printf("第一次讀: %x\n", first)
	fmt.Printf("第二次讀: %x\n", second)
	fmt.Printf("一次取完: %x\n", sha3.SumSHAKE128([]byte("hello"), 16))
}
```

輸出：

```text
第一次讀: 8eb4b6a932f28033
第二次讀: 5ee1a279f8c208a3
一次取完: 8eb4b6a932f280335ee1a279f8c208a3
```

### 搭配 crypto.Hash 與 crypto/hmac

匯入 `crypto/sha3` 後，`crypto.SHA3_256` 等常數就能用 `New()` 建立雜湊（見 [crypto](/pkg-crypto)）。

[crypto/hmac](/pkg-crypto-hmac) 的 `hmac.New` 需要 `func() hash.Hash`，而 `sha3.New256` 回傳的是 `*sha3.SHA3`，函式型別不同，不能直接傳入，要包一層匿名函式。

範例：

```go
package main

import (
	"crypto"
	"crypto/hmac"
	"crypto/sha3"
	"fmt"
	"hash"
)

func main() {
	h := crypto.SHA3_256.New()
	h.Write([]byte("hello"))
	fmt.Printf("crypto.SHA3_256: %x\n", h.Sum(nil))

	newSHA3 := func() hash.Hash { return sha3.New256() }
	mac := hmac.New(newSHA3, []byte("secret"))
	mac.Write([]byte("hello"))
	fmt.Println("HMAC-SHA3-256 長度:", len(mac.Sum(nil)))
}
```

輸出：

```text
crypto.SHA3_256: 3338be694f50c5f338814986cdf0686453a888b84f424d792af4b9202398f392
HMAC-SHA3-256 長度: 32
```

## 重點整理

- `crypto/sha3` 是 Go 1.24 起的標準庫套件，取代 `golang.org/x/crypto/sha3`
- SHA3-256 與 SHA-256 是不同演算法，結果不同；沒有特別要求時 SHA-256 較普及
- 一次算完用 `Sum224`／`Sum256`／`Sum384`／`Sum512`，串流用 `New256` 等；`sha3.SHA3` 零值即 SHA3-256
- 需要任意長度輸出用 SHAKE：`SumSHAKE256(data, n)` 或 `NewSHAKE256` + `Read`
- `SHAKE` 開始 `Read` 後再 `Write` 會 panic
- 搭配 `hmac.New` 要包成 `func() hash.Hash`

## 資料來源

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