crypto/cipher

最後更新


crypto/cipher 提供區塊加密器的加密模式,最重要的是 AEAD(GCM):一次完成加密與竄改偵測。

這個套件做什麼


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

匯入


  1. 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。
簽名:
  1. func NewGCM(cipher Block) (AEAD, error)
  2. type AEAD interface {
  3. NonceSize() int
  4. Overhead() int
  5. Seal(dst, nonce, plaintext, additionalData []byte) []byte
  6. Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
  7. }

範例:
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "fmt"
  7. )
  8. func main() {
  9. key := make([]byte, 32)
  10. rand.Read(key)
  11. block, err := aes.NewCipher(key)
  12. if err != nil {
  13. fmt.Println("建立失敗:", err)
  14. return
  15. }
  16. gcm, err := cipher.NewGCM(block)
  17. if err != nil {
  18. fmt.Println("建立 GCM 失敗:", err)
  19. return
  20. }
  21. nonce := make([]byte, gcm.NonceSize())
  22. rand.Read(nonce)
  23. plaintext := []byte("hello, gcm")
  24. ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
  25. decrypted, err := gcm.Open(nil, nonce, ciphertext, nil)
  26. if err != nil {
  27. fmt.Println("解密失敗:", err)
  28. return
  29. }
  30. fmt.Println("NonceSize:", gcm.NonceSize())
  31. fmt.Println("Overhead:", gcm.Overhead())
  32. fmt.Println("明文長度:", len(plaintext), "密文長度:", len(ciphertext))
  33. fmt.Println("解密結果:", string(decrypted))
  34. }

輸出:
  1. NonceSize: 12
  2. Overhead: 16
  3. 明文長度: 10 密文長度: 26
  4. 解密結果: hello, gcm

把 nonce 存在密文前面


nonce 不需要保密,但解密時一定要有。最常見的做法:加密時把 nonce 放在輸出最前面,解密時先切出前 NonceSize() 個 bytes 當 nonce。
技巧:gcm.Seal(nonce, nonce, plaintext, nil) 的第一個參數 dst 傳 nonce,加密結果就會直接附加在 nonce 後面,一行完成「nonce + 密文 + tag」。
因為每次 nonce 都是隨機的,同一段明文加密兩次會得到不同結果,攻擊者無法從密文看出「這兩筆資料內容相同」。
解密前要先檢查長度,否則資料太短時切片會 panic。
範例:
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "errors"
  7. "fmt"
  8. )
  9. func encrypt(gcm cipher.AEAD, plaintext []byte) []byte {
  10. nonce := make([]byte, gcm.NonceSize())
  11. rand.Read(nonce)
  12. return gcm.Seal(nonce, nonce, plaintext, nil)
  13. }
  14. func decrypt(gcm cipher.AEAD, data []byte) ([]byte, error) {
  15. n := gcm.NonceSize()
  16. if len(data) < n {
  17. return nil, errors.New("[Invalid] ciphertext: too short")
  18. }
  19. nonce, ciphertext := data[:n], data[n:]
  20. return gcm.Open(nil, nonce, ciphertext, nil)
  21. }
  22. func main() {
  23. key := make([]byte, 32)
  24. rand.Read(key)
  25. block, _ := aes.NewCipher(key)
  26. gcm, _ := cipher.NewGCM(block)
  27. a := encrypt(gcm, []byte("同一段文字"))
  28. b := encrypt(gcm, []byte("同一段文字"))
  29. fmt.Println("兩次密文相同:", string(a) == string(b))
  30. fmt.Println("輸出長度:", len(a))
  31. plain, err := decrypt(gcm, a)
  32. fmt.Println("解密:", string(plain), err)
  33. _, err = decrypt(gcm, []byte("abc"))
  34. fmt.Println("太短:", err)
  35. }

輸出:
  1. 兩次密文相同: false
  2. 輸出長度: 43
  3. 解密: 同一段文字 <nil>
  4. 太短: [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 撞號。
簽名:
  1. func NewGCMWithRandomNonce(cipher Block) (AEAD, error)

範例:
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "fmt"
  7. )
  8. func main() {
  9. key := make([]byte, 32)
  10. rand.Read(key)
  11. block, err := aes.NewCipher(key)
  12. if err != nil {
  13. fmt.Println("建立失敗:", err)
  14. return
  15. }
  16. gcm, err := cipher.NewGCMWithRandomNonce(block)
  17. if err != nil {
  18. fmt.Println("建立 GCM 失敗:", err)
  19. return
  20. }
  21. fmt.Println("NonceSize:", gcm.NonceSize())
  22. fmt.Println("Overhead:", gcm.Overhead())
  23. sealed := gcm.Seal(nil, nil, []byte("hello"), nil)
  24. fmt.Println("密文長度:", len(sealed))
  25. plain, err := gcm.Open(nil, nil, sealed, nil)
  26. fmt.Println("解密:", string(plain), err)
  27. }

輸出:
  1. NonceSize: 0
  2. Overhead: 28
  3. 密文長度: 33
  4. 解密: hello <nil>

附加資料(additional data)


Seal/Open 的最後一個參數是附加資料:它不會被加密,也不會存進密文,但會被 tag 保護。解密時必須提供完全相同的值,否則失敗。
用途:把密文「綁定」到它的情境。例如資料庫裡 A 使用者的加密病歷,以使用者 ID 當附加資料;就算有人把這筆密文搬到 B 使用者的欄位,用 B 的 ID 解密也會失敗。
範例:
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "fmt"
  7. )
  8. func main() {
  9. key := make([]byte, 32)
  10. rand.Read(key)
  11. block, _ := aes.NewCipher(key)
  12. gcm, _ := cipher.NewGCMWithRandomNonce(block)
  13. userA := []byte("user:1001")
  14. userB := []byte("user:2002")
  15. sealed := gcm.Seal(nil, nil, []byte("A 的病歷"), userA)
  16. plain, err := gcm.Open(nil, nil, sealed, userA)
  17. fmt.Println("正確 AAD:", string(plain), err)
  18. _, err = gcm.Open(nil, nil, sealed, userB)
  19. fmt.Println("錯誤 AAD:", err)
  20. }

輸出:
  1. 正確 AAD: A 的病歷 <nil>
  2. 錯誤 AAD: cipher: message authentication failed

竄改偵測:Open 的錯誤


Open 回傳錯誤只有一種意思:資料不可信。可能是密文被改過、金鑰不對、nonce 或附加資料不符。錯誤訊息刻意不說明是哪一種,以免洩漏資訊給攻擊者。
收到錯誤時,丟棄整筆資料,不要使用 Open 回傳的任何內容。
範例:
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "fmt"
  7. )
  8. func main() {
  9. key := make([]byte, 32)
  10. rand.Read(key)
  11. block, _ := aes.NewCipher(key)
  12. gcm, _ := cipher.NewGCMWithRandomNonce(block)
  13. sealed := gcm.Seal(nil, nil, []byte("金額: 100"), nil)
  14. tampered := append([]byte(nil), sealed...)
  15. tampered[len(tampered)-1] ^= 0x01
  16. _, err := gcm.Open(nil, nil, tampered, nil)
  17. fmt.Println("竄改後:", err)
  18. otherKey := make([]byte, 32)
  19. rand.Read(otherKey)
  20. otherBlock, _ := aes.NewCipher(otherKey)
  21. otherGCM, _ := cipher.NewGCMWithRandomNonce(otherBlock)
  22. _, err = otherGCM.Open(nil, nil, sealed, nil)
  23. fmt.Println("錯誤金鑰:", err)
  24. }

輸出:
  1. 竄改後: cipher: message authentication failed
  2. 錯誤金鑰: cipher: message authentication failed

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

cipher.Block 介面


Block 是所有區塊加密器的共同介面,aes.NewCipher 回傳的就是它。GCM 等模式只依賴這個介面。
範例用全零金鑰與全零 nonce 加密 16 個零 bytes,這是 GCM 規格的公開測試案例,結果固定,前 16 bytes 是密文、後 16 bytes 是 tag。這只是為了讓輸出可重現;實務上 nonce 絕不能固定,否則同一把金鑰第二次加密就會洩漏資訊。
簽名:
  1. type Block interface {
  2. BlockSize() int
  3. Encrypt(dst, src []byte)
  4. Decrypt(dst, src []byte)
  5. }

範例:
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "encoding/hex"
  6. "fmt"
  7. )
  8. func main() {
  9. key := make([]byte, 16)
  10. nonce := make([]byte, 12)
  11. block, err := aes.NewCipher(key)
  12. if err != nil {
  13. fmt.Println("建立失敗:", err)
  14. return
  15. }
  16. var b cipher.Block = block
  17. fmt.Println("BlockSize:", b.BlockSize())
  18. gcm, err := cipher.NewGCM(b)
  19. if err != nil {
  20. fmt.Println("建立 GCM 失敗:", err)
  21. return
  22. }
  23. out := gcm.Seal(nil, nonce, make([]byte, 16), nil)
  24. fmt.Println(hex.EncodeToString(out))
  25. }

輸出:
  1. BlockSize: 16
  2. 0388dace60b6a392f328c2b971b2fe78ab6e47d42cec13bdf53a67b21257bddf

重點整理


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

資料來源