crypto

最後更新


crypto 套件定義整個密碼學家族共用的常數與介面,本身不實作任何演算法。

這個套件做什麼


Go 的密碼學功能拆成很多子套件:crypto/sha256 負責雜湊、crypto/aes 負責對稱加密、crypto/ed25519 負責簽章...。crypto 是這些子套件的「共同語言」:
  • crypto.Hash:用一個常數代表某種雜湊演算法(如 crypto.SHA256),讓簽章等 API 不必直接依賴特定雜湊套件
  • crypto.PublicKey、crypto.PrivateKey:代表「某種演算法的公鑰/私鑰」
  • crypto.Signer、crypto.Decrypter、crypto.Encapsulator 等介面(interface):讓你的程式只依賴「能簽章的東西」,不必關心背後是 RSA、ECDSA、Ed25519,甚至是存在硬體裝置裡的金鑰

什麼時候會直接用到 crypto?
情境用到的東西
寫一個函式,接受任何能簽章的金鑰crypto.Signer
簽章時指定使用哪種雜湊crypto.SHA256 等 crypto.Hash 常數
依設定檔動態選擇雜湊演算法crypto.Hash.New()

如果只是要算雜湊或加解密,直接用對應的子套件即可,例如 crypto/sha256、crypto/cipher。介面的基本觀念見介面基礎。

匯入


  1. import "crypto"

常用 API


crypto.Hash 與 Size、String


crypto.Hash 是一個整數型別,每個常數代表一種雜湊演算法。Size() 回傳該演算法的摘要長度(bytes),String() 回傳名稱。Size() 不需要匯入對應的實作套件也能用。
簽名:
  1. type Hash uint
  2. func (h Hash) Size() int
  3. func (h Hash) String() string

範例:
  1. package main
  2. import (
  3. "crypto"
  4. "fmt"
  5. )
  6. func main() {
  7. for _, h := range []crypto.Hash{crypto.MD5, crypto.SHA256, crypto.SHA512, crypto.SHA3_256} {
  8. fmt.Printf("%-9s 摘要長度 %d bytes\n", h.String(), h.Size())
  9. }
  10. }

輸出:
  1. MD5 摘要長度 16 bytes
  2. SHA-256 摘要長度 32 bytes
  3. SHA-512 摘要長度 64 bytes
  4. SHA3-256 摘要長度 32 bytes

Hash.Available 與 Hash.New


crypto.Hash 只是一個代號,真正的演算法在子套件裡。子套件被匯入時會在 init 中呼叫 crypto.RegisterHash 登記自己,之後 Hash.New() 才能建立對應的雜湊物件。
只想登記、不直接使用子套件的名稱時,用空白匯入 _ "crypto/sha256"。Available() 回報某個雜湊是否已連結進程式。
注意:對沒有連結進程式的雜湊呼叫 New() 會 panic,不確定時先用 Available() 檢查。
簽名:
  1. func (h Hash) Available() bool
  2. func (h Hash) New() hash.Hash

範例:
  1. package main
  2. import (
  3. "crypto"
  4. _ "crypto/sha256"
  5. "encoding/hex"
  6. "fmt"
  7. )
  8. func main() {
  9. fmt.Println("SHA256 可用:", crypto.SHA256.Available())
  10. fmt.Println("SHA512 可用:", crypto.SHA512.Available())
  11. h := crypto.SHA256.New()
  12. h.Write([]byte("hello"))
  13. fmt.Println(hex.EncodeToString(h.Sum(nil)))
  14. }

輸出:
  1. SHA256 可用: true
  2. SHA512 可用: false
  3. 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

這個程式沒有匯入 crypto/sha512,所以 SHA512 不可用。New() 回傳的是 hash.Hash 介面。

crypto.Signer


Signer 介面代表「一把私鑰,能產生簽章」。標準庫的 RSA、ECDSA、Ed25519 私鑰都實作了它。把參數型別寫成 crypto.Signer,函式就能接受任何一種私鑰。
opts 參數告訴 Sign 訊息是用哪種雜湊處理過的;Ed25519 要直接簽原文,所以傳 crypto.Hash(0)。範例用固定種子產生金鑰,因此每次執行結果一樣(Ed25519 簽章本身是確定性的);實務上金鑰要用 crypto/rand 產生。
簽名:
  1. type Signer interface {
  2. Public() PublicKey
  3. Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
  4. }

範例:
  1. package main
  2. import (
  3. "crypto"
  4. "crypto/ed25519"
  5. "crypto/sha256"
  6. "fmt"
  7. )
  8. func signWith(s crypto.Signer, msg []byte) ([]byte, error) {
  9. return s.Sign(nil, msg, crypto.Hash(0))
  10. }
  11. func main() {
  12. seed := sha256.Sum256([]byte("demo seed"))
  13. priv := ed25519.NewKeyFromSeed(seed[:])
  14. msg := []byte("轉帳 100 元給小明")
  15. sig, err := signWith(priv, msg)
  16. if err != nil {
  17. fmt.Println("簽章失敗:", err)
  18. return
  19. }
  20. pub := priv.Public().(ed25519.PublicKey)
  21. fmt.Println("簽章長度:", len(sig))
  22. fmt.Println("驗證原文:", ed25519.Verify(pub, msg, sig))
  23. fmt.Println("驗證竄改:", ed25519.Verify(pub, []byte("轉帳 900 元給小明"), sig))
  24. }

輸出:
  1. 簽章長度: 64
  2. 驗證原文: true
  3. 驗證竄改: false

更多 Ed25519 用法見 crypto/ed25519。

crypto.SignMessage


SignMessage(Go 1.25 起)幫你處理「要不要先雜湊」:如果金鑰實作了 MessageSigner,直接把原文交給它;否則依 opts.HashFunc() 先雜湊訊息,再呼叫 Sign。opts 是 crypto.Hash(0) 時代表不雜湊,原文直接傳給 Sign。
簽名:
  1. func SignMessage(signer Signer, rand io.Reader, msg []byte, opts SignerOpts) (signature []byte, err error)

範例:
  1. package main
  2. import (
  3. "crypto"
  4. "crypto/ed25519"
  5. "fmt"
  6. )
  7. func main() {
  8. priv := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize))
  9. msg := []byte("hello")
  10. sig, err := crypto.SignMessage(priv, nil, msg, crypto.Hash(0))
  11. if err != nil {
  12. fmt.Println("簽章失敗:", err)
  13. return
  14. }
  15. fmt.Println("簽章長度:", len(sig))
  16. fmt.Println("驗證結果:", ed25519.Verify(priv.Public().(ed25519.PublicKey), msg, sig))
  17. }

輸出:
  1. 簽章長度: 64
  2. 驗證結果: true

crypto.PublicKey 與 crypto.PrivateKey


這兩個型別都是 any,因為不同演算法的金鑰結構完全不同。標準庫所有公鑰都有 Equal(crypto.PublicKey) bool 方法,所有私鑰都有 Public() 與 Equal 方法;要使用這些方法,先用型別斷言轉成具體型別或小介面。
簽名:
  1. type PublicKey any
  2. type PrivateKey any

範例:
  1. package main
  2. import (
  3. "crypto"
  4. "crypto/ed25519"
  5. "fmt"
  6. )
  7. type equaler interface {
  8. Equal(x crypto.PublicKey) bool
  9. }
  10. func main() {
  11. seedA := make([]byte, ed25519.SeedSize)
  12. seedB := make([]byte, ed25519.SeedSize)
  13. seedB[0] = 1
  14. a := ed25519.NewKeyFromSeed(seedA)
  15. b := ed25519.NewKeyFromSeed(seedB)
  16. var pubA crypto.PublicKey = a.Public()
  17. var pubB crypto.PublicKey = b.Public()
  18. fmt.Printf("型別: %T\n", pubA)
  19. fmt.Println("A 與自己相同:", pubA.(equaler).Equal(a.Public()))
  20. fmt.Println("A 與 B 相同:", pubA.(equaler).Equal(pubB))
  21. }

輸出:
  1. 型別: ed25519.PublicKey
  2. A 與自己相同: true
  3. A 與 B 相同: false

比較金鑰請用 Equal,不要用 ==:很多金鑰型別是切片或含指標的結構體,== 不能用或比的不是內容。

crypto.Encapsulator 與 crypto.Decapsulator


KEM(Key Encapsulation Mechanism,金鑰封裝機制)讓雙方安全地得到同一把共享金鑰:一方用公鑰「封裝」出共享金鑰與密文,把密文傳給對方;對方用私鑰「解封裝」密文,得到同一把共享金鑰。
Encapsulator、Decapsulator(Go 1.26 起)是 KEM 的通用介面,crypto/mlkem 的金鑰實作了它們。每次執行金鑰不同,範例只印長度與比對結果。
簽名:
  1. type Encapsulator interface {
  2. Bytes() []byte
  3. Encapsulate() (sharedKey, ciphertext []byte)
  4. }
  5. type Decapsulator interface {
  6. Encapsulator() Encapsulator
  7. Decapsulate(ciphertext []byte) (sharedKey []byte, err error)
  8. }

範例:
  1. package main
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/mlkem"
  6. "fmt"
  7. )
  8. func main() {
  9. dk, err := mlkem.GenerateKey768()
  10. if err != nil {
  11. fmt.Println("產生金鑰失敗:", err)
  12. return
  13. }
  14. var dec crypto.Decapsulator = dk
  15. var enc crypto.Encapsulator = dec.Encapsulator()
  16. sharedA, ciphertext := enc.Encapsulate()
  17. sharedB, err := dec.Decapsulate(ciphertext)
  18. if err != nil {
  19. fmt.Println("解封裝失敗:", err)
  20. return
  21. }
  22. fmt.Println("共享金鑰長度:", len(sharedA))
  23. fmt.Println("密文長度:", len(ciphertext))
  24. fmt.Println("雙方金鑰相同:", bytes.Equal(sharedA, sharedB))
  25. }

輸出:
  1. 共享金鑰長度: 32
  2. 密文長度: 1088
  3. 雙方金鑰相同: true

重點整理


  • crypto 只定義共用常數與介面,演算法實作在各子套件
  • crypto.Hash 常數代表雜湊演算法;New() 需要先匯入對應子套件,否則會 panic,可用 Available() 檢查
  • 參數寫成 crypto.Signer,函式就能接受 RSA、ECDSA、Ed25519 等各種私鑰
  • PublicKey、PrivateKey 是 any,比較金鑰用 Equal 方法
  • SignMessage(Go 1.25 起)、Encapsulator/Decapsulator(Go 1.26 起)是較新的 API,見 /go-1-25、/go-1-26

資料來源