# crypto/sha256

`crypto/sha256` 計算 SHA-256（與 SHA-224）雜湊值，把任意長度的資料變成固定 32 bytes 的「指紋」。

## 這個套件做什麼

雜湊函式（hash function）像是資料的指紋機：

- 同樣的輸入永遠得到同樣的輸出
- 輸入只差一個字元，輸出就完全不同
- 從輸出幾乎不可能反推出輸入，也幾乎不可能找到兩個輸入得到相同輸出

SHA-256 是目前最常用的安全雜湊演算法，常見用途：

| 用途 | 說明 |
| --- | --- |
| 檔案校驗 | 下載後比對官方公布的 SHA-256，確認檔案沒被竄改 |
| 內容定址 | 以雜湊值當檔案或快取的 key，相同內容只存一份 |
| 簽章與 HMAC 的基礎 | [crypto/hmac](/pkg-crypto-hmac)、RSA／ECDSA 簽章都會搭配 SHA-256 |

和相近套件的差別：

- [crypto/sha3](/pkg-crypto-sha3)：另一套設計的安全雜湊，長度選擇相同，用在要求 SHA-3 的規範中
- [crypto/md5](/pkg-crypto-md5)：已被破解，只能做非安全用途的校驗
- [hash/crc32](/pkg-hash-crc32)：只偵測意外損壞，不防刻意竄改，但速度快

注意：SHA-256 不適合直接拿來存使用者密碼，因為它算得太快，攻擊者能大量暴力嘗試。密碼請用 [x/crypto](/lib-x-crypto) 的 bcrypt 或 argon2。

## 匯入

```go
import "crypto/sha256"
```

## 常用 API

### sha256.Sum256

一次算出整段資料的 SHA-256。回傳值是固定長度的[陣列](/composite-arrays) `[32]byte`，不是切片。用 `%x` 可以印成十六進位字串。

簽名：

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

範例：

```go
package main

import (
	"crypto/sha256"
	"fmt"
)

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

輸出：

```text
型別: [32]uint8
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
ce06092fb948d9ffac7d1a376e404b26b7575bcc11ee05a4615fef4fec3a308b
```

只多一個 `!`，雜湊值就完全不同。`byte` 是 `uint8` 的別名，所以型別印成 `[32]uint8`。

### sha256.New

資料很大或分批到達時，用 `New` 建立一個 [hash.Hash](/pkg-hash)，持續 `Write` 寫入，最後 `Sum(nil)` 取得結果。`hash.Hash` 實作了 `io.Writer`，所以能直接當 `io.Copy` 的目的地。

分段寫入與一次寫入的結果相同。`Reset()` 讓同一個物件重新開始計算。

簽名：

```go
func New() hash.Hash
```

範例：

```go
package main

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

func main() {
	h := sha256.New()
	h.Write([]byte("hel"))
	h.Write([]byte("lo"))
	fmt.Printf("分段寫入: %x\n", h.Sum(nil))

	h.Reset()
	io.Copy(h, strings.NewReader("hello"))
	fmt.Printf("io.Copy : %x\n", h.Sum(nil))
}
```

輸出：

```text
分段寫入: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
io.Copy : 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
```

`Sum(b)` 會把雜湊值附加到 `b` 後面再回傳，傳 `nil` 就是取得一個新的切片。`Sum` 不會改變內部狀態，之後還能繼續 `Write`。

### 計算檔案的 SHA-256

結合 `os.Open` 與 `io.Copy`，可以邊讀檔邊計算，不必把整個檔案載入記憶體。這是驗證下載檔案的標準做法。範例在暫存目錄建立檔案，結束時移除。

範例：

```go
package main

import (
	"crypto/sha256"
	"fmt"
	"io"
	"os"
	"path/filepath"
)

func fileSHA256(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()

	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}
	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

func main() {
	dir, err := os.MkdirTemp("", "sha256-demo")
	if err != nil {
		fmt.Println("建立暫存目錄失敗:", err)
		return
	}
	defer os.RemoveAll(dir)

	path := filepath.Join(dir, "data.txt")
	if err := os.WriteFile(path, []byte("hello"), 0o644); err != nil {
		fmt.Println("寫檔失敗:", err)
		return
	}

	sum, err := fileSHA256(path)
	if err != nil {
		fmt.Println("計算失敗:", err)
		return
	}
	fmt.Println(sum)

	expected := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
	fmt.Println("與預期相符:", sum == expected)
}
```

輸出：

```text
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
與預期相符: true
```

### 比較雜湊值

`Sum256` 回傳陣列，陣列可以直接用 `==` 比較，也可以當映射（map）的 key。需要較短的識別碼時，可以取前幾個 bytes 再轉十六進位，但越短越容易撞號。

比較的是公開的檔案雜湊時，`==` 就夠了；比較的是 HMAC 這類需要保密的驗證碼時，請改用 `hmac.Equal`，見 [crypto/hmac](/pkg-crypto-hmac)。

範例：

```go
package main

import (
	"crypto/sha256"
	"fmt"
)

func main() {
	a := sha256.Sum256([]byte("report-v1.pdf 的內容"))
	b := sha256.Sum256([]byte("report-v1.pdf 的內容"))
	c := sha256.Sum256([]byte("report-v2.pdf 的內容"))

	fmt.Println("a == b:", a == b)
	fmt.Println("a == c:", a == c)

	key := fmt.Sprintf("%x", a[:8])
	fmt.Println("短識別碼:", key)
}
```

輸出：

```text
a == b: true
a == c: false
短識別碼: 271dd5698309c6c2
```

### sha256.Sum224 與常數

SHA-224 是 SHA-256 的截短版本，摘要長度 28 bytes，用在要求 SHA-224 的規範中。`New224()` 是對應的串流版本。

套件常數：

| 常數 | 值 | 意義 |
| --- | --- | --- |
| `Size` | 32 | SHA-256 摘要長度 |
| `Size224` | 28 | SHA-224 摘要長度 |
| `BlockSize` | 64 | 演算法內部的區塊大小 |

簽名：

```go
func Sum224(data []byte) [Size224]byte
func New224() hash.Hash
```

範例：

```go
package main

import (
	"crypto/sha256"
	"fmt"
)

func main() {
	fmt.Println("Size:", sha256.Size)
	fmt.Println("Size224:", sha256.Size224)
	fmt.Println("BlockSize:", sha256.BlockSize)

	sum := sha256.Sum224([]byte("hello"))
	fmt.Println("Sum224 長度:", len(sum))
	fmt.Printf("%x\n", sum)
}
```

輸出：

```text
Size: 32
Size224: 28
BlockSize: 64
Sum224 長度: 28
ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193
```

## 重點整理

- 一次算完用 `Sum256`，回傳 `[32]byte` 陣列，可直接 `==` 比較
- 大資料或串流用 `New()` + `Write`／`io.Copy` + `Sum(nil)`
- 檔案校驗用 `io.Copy` 邊讀邊算，不必整檔載入
- 印成十六進位用 `%x` 或 [encoding/hex](/pkg-encoding-hex)
- 不要用 SHA-256 直接存密碼，改用 [x/crypto](/lib-x-crypto) 的 bcrypt／argon2

## 資料來源

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