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。介面的基本觀念見介面基礎。
匯入
- import "crypto"
常用 API
crypto.Hash 與 Size、String
crypto.Hash 是一個整數型別,每個常數代表一種雜湊演算法。Size() 回傳該演算法的摘要長度(bytes),String() 回傳名稱。Size() 不需要匯入對應的實作套件也能用。簽名:
- type Hash uint
- func (h Hash) Size() int
- func (h Hash) String() string
範例:
- package main
- import (
- "crypto"
- "fmt"
- )
- func main() {
- for _, h := range []crypto.Hash{crypto.MD5, crypto.SHA256, crypto.SHA512, crypto.SHA3_256} {
- fmt.Printf("%-9s 摘要長度 %d bytes\n", h.String(), h.Size())
- }
- }
輸出:
- MD5 摘要長度 16 bytes
- SHA-256 摘要長度 32 bytes
- SHA-512 摘要長度 64 bytes
- SHA3-256 摘要長度 32 bytes
Hash.Available 與 Hash.New
crypto.Hash 只是一個代號,真正的演算法在子套件裡。子套件被匯入時會在 init 中呼叫 crypto.RegisterHash 登記自己,之後 Hash.New() 才能建立對應的雜湊物件。只想登記、不直接使用子套件的名稱時,用空白匯入
_ "crypto/sha256"。Available() 回報某個雜湊是否已連結進程式。注意:對沒有連結進程式的雜湊呼叫
New() 會 panic,不確定時先用 Available() 檢查。簽名:
- func (h Hash) Available() bool
- func (h Hash) New() hash.Hash
範例:
- package main
- import (
- "crypto"
- _ "crypto/sha256"
- "encoding/hex"
- "fmt"
- )
- func main() {
- fmt.Println("SHA256 可用:", crypto.SHA256.Available())
- fmt.Println("SHA512 可用:", crypto.SHA512.Available())
- h := crypto.SHA256.New()
- h.Write([]byte("hello"))
- fmt.Println(hex.EncodeToString(h.Sum(nil)))
- }
輸出:
- SHA256 可用: true
- SHA512 可用: false
- 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
這個程式沒有匯入
crypto/sha512,所以 SHA512 不可用。New() 回傳的是 hash.Hash 介面。crypto.Signer
Signer 介面代表「一把私鑰,能產生簽章」。標準庫的 RSA、ECDSA、Ed25519 私鑰都實作了它。把參數型別寫成 crypto.Signer,函式就能接受任何一種私鑰。opts 參數告訴 Sign 訊息是用哪種雜湊處理過的;Ed25519 要直接簽原文,所以傳 crypto.Hash(0)。範例用固定種子產生金鑰,因此每次執行結果一樣(Ed25519 簽章本身是確定性的);實務上金鑰要用 crypto/rand 產生。簽名:
- type Signer interface {
- Public() PublicKey
- Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
- }
範例:
- package main
- import (
- "crypto"
- "crypto/ed25519"
- "crypto/sha256"
- "fmt"
- )
- func signWith(s crypto.Signer, msg []byte) ([]byte, error) {
- return s.Sign(nil, msg, crypto.Hash(0))
- }
- func main() {
- seed := sha256.Sum256([]byte("demo seed"))
- priv := ed25519.NewKeyFromSeed(seed[:])
- msg := []byte("轉帳 100 元給小明")
- sig, err := signWith(priv, msg)
- if err != nil {
- fmt.Println("簽章失敗:", err)
- return
- }
- pub := priv.Public().(ed25519.PublicKey)
- fmt.Println("簽章長度:", len(sig))
- fmt.Println("驗證原文:", ed25519.Verify(pub, msg, sig))
- fmt.Println("驗證竄改:", ed25519.Verify(pub, []byte("轉帳 900 元給小明"), sig))
- }
輸出:
- 簽章長度: 64
- 驗證原文: true
- 驗證竄改: false
更多 Ed25519 用法見 crypto/ed25519。
crypto.SignMessage
SignMessage(Go 1.25 起)幫你處理「要不要先雜湊」:如果金鑰實作了 MessageSigner,直接把原文交給它;否則依 opts.HashFunc() 先雜湊訊息,再呼叫 Sign。opts 是 crypto.Hash(0) 時代表不雜湊,原文直接傳給 Sign。簽名:
- func SignMessage(signer Signer, rand io.Reader, msg []byte, opts SignerOpts) (signature []byte, err error)
範例:
- package main
- import (
- "crypto"
- "crypto/ed25519"
- "fmt"
- )
- func main() {
- priv := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize))
- msg := []byte("hello")
- sig, err := crypto.SignMessage(priv, nil, msg, crypto.Hash(0))
- if err != nil {
- fmt.Println("簽章失敗:", err)
- return
- }
- fmt.Println("簽章長度:", len(sig))
- fmt.Println("驗證結果:", ed25519.Verify(priv.Public().(ed25519.PublicKey), msg, sig))
- }
輸出:
- 簽章長度: 64
- 驗證結果: true
crypto.PublicKey 與 crypto.PrivateKey
這兩個型別都是
any,因為不同演算法的金鑰結構完全不同。標準庫所有公鑰都有 Equal(crypto.PublicKey) bool 方法,所有私鑰都有 Public() 與 Equal 方法;要使用這些方法,先用型別斷言轉成具體型別或小介面。簽名:
- type PublicKey any
- type PrivateKey any
範例:
- package main
- import (
- "crypto"
- "crypto/ed25519"
- "fmt"
- )
- type equaler interface {
- Equal(x crypto.PublicKey) bool
- }
- func main() {
- seedA := make([]byte, ed25519.SeedSize)
- seedB := make([]byte, ed25519.SeedSize)
- seedB[0] = 1
- a := ed25519.NewKeyFromSeed(seedA)
- b := ed25519.NewKeyFromSeed(seedB)
- var pubA crypto.PublicKey = a.Public()
- var pubB crypto.PublicKey = b.Public()
- fmt.Printf("型別: %T\n", pubA)
- fmt.Println("A 與自己相同:", pubA.(equaler).Equal(a.Public()))
- fmt.Println("A 與 B 相同:", pubA.(equaler).Equal(pubB))
- }
輸出:
- 型別: ed25519.PublicKey
- A 與自己相同: true
- A 與 B 相同: false
比較金鑰請用
Equal,不要用 ==:很多金鑰型別是切片或含指標的結構體,== 不能用或比的不是內容。crypto.Encapsulator 與 crypto.Decapsulator
KEM(Key Encapsulation Mechanism,金鑰封裝機制)讓雙方安全地得到同一把共享金鑰:一方用公鑰「封裝」出共享金鑰與密文,把密文傳給對方;對方用私鑰「解封裝」密文,得到同一把共享金鑰。
Encapsulator、Decapsulator(Go 1.26 起)是 KEM 的通用介面,crypto/mlkem 的金鑰實作了它們。每次執行金鑰不同,範例只印長度與比對結果。簽名:
- type Encapsulator interface {
- Bytes() []byte
- Encapsulate() (sharedKey, ciphertext []byte)
- }
- type Decapsulator interface {
- Encapsulator() Encapsulator
- Decapsulate(ciphertext []byte) (sharedKey []byte, err error)
- }
範例:
- package main
- import (
- "bytes"
- "crypto"
- "crypto/mlkem"
- "fmt"
- )
- func main() {
- dk, err := mlkem.GenerateKey768()
- if err != nil {
- fmt.Println("產生金鑰失敗:", err)
- return
- }
- var dec crypto.Decapsulator = dk
- var enc crypto.Encapsulator = dec.Encapsulator()
- sharedA, ciphertext := enc.Encapsulate()
- sharedB, err := dec.Decapsulate(ciphertext)
- if err != nil {
- fmt.Println("解封裝失敗:", err)
- return
- }
- fmt.Println("共享金鑰長度:", len(sharedA))
- fmt.Println("密文長度:", len(ciphertext))
- fmt.Println("雙方金鑰相同:", bytes.Equal(sharedA, sharedB))
- }
輸出:
- 共享金鑰長度: 32
- 密文長度: 1088
- 雙方金鑰相同: 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