crypto/ed25519

最後更新


crypto/ed25519 實作 Ed25519 數位簽章:金鑰短、速度快、API 簡單,是新系統做簽章的首選。

這個套件做什麼


數位簽章(digital signature)讓接收方確認「資料是誰送的、途中有沒有被改」。簽署者用私鑰(private key)簽章,任何人用公鑰(public key)驗證。
Ed25519 是建立在 Curve25519 橢圓曲線上的簽章演算法(RFC 8032)。和 crypto/ecdsa、crypto/rsa 比起來,它有幾個對新手友善的特性:
特性Ed25519ECDSA P-256RSA 2048
公鑰長度32 位元組65 位元組(未壓縮)約 270 位元組(DER)
簽章長度固定 64 位元組不固定,最長 72256 位元組
簽章前要自己雜湊嗎不用,直接傳原始訊息要要
同一訊息簽兩次結果相同(確定性)預設不同PSS 不同

什麼時候用:
  • 自己設計的 API 簽章、Webhook 驗證、軟體發佈簽章
  • SSH 金鑰(ssh-ed25519)、JWT 的 EdDSA

什麼時候不用:對方系統只接受 RSA 或 NIST 曲線(例如某些 FIPS 環境),就改用 crypto/rsa 或 crypto/ecdsa。
金鑰型別 PublicKey、PrivateKey 本質上都是 []byte,可以直接存取長度、轉成十六進位。要存成 PEM 檔,用 crypto/x509 的 MarshalPKCS8PrivateKey/MarshalPKIXPublicKey。

匯入


  1. import "crypto/ed25519"

常用 API


GenerateKey


產生一組新的公鑰與私鑰。random 傳 nil 時使用安全的系統亂數;慣例也可傳 crypto/rand 的 rand.Reader。
套件提供四個長度常數:PublicKeySize(32)、PrivateKeySize(64)、SignatureSize(64)、SeedSize(32)。
簽名:
  1. func GenerateKey(random io.Reader) (PublicKey, PrivateKey, error)

範例:
  1. package main
  2. import (
  3. "crypto/ed25519"
  4. "crypto/rand"
  5. "fmt"
  6. )
  7. func main() {
  8. pub, priv, err := ed25519.GenerateKey(rand.Reader)
  9. if err != nil {
  10. fmt.Println("error:", err)
  11. return
  12. }
  13. fmt.Println("公鑰長度:", len(pub), "PublicKeySize =", ed25519.PublicKeySize)
  14. fmt.Println("私鑰長度:", len(priv), "PrivateKeySize =", ed25519.PrivateKeySize)
  15. fmt.Println("種子長度:", len(priv.Seed()), "SeedSize =", ed25519.SeedSize)
  16. }

輸出:
  1. 公鑰長度: 32 PublicKeySize = 32
  2. 私鑰長度: 64 PrivateKeySize = 64
  3. 種子長度: 32 SeedSize = 32

每次執行金鑰都不同,所以這裡只印長度。

NewKeyFromSeed 與 PrivateKey.Seed


Ed25519 的私鑰其實可以完全由一個 32 位元組的「種子(seed)」推導出來,RFC 8032 所說的私鑰就是這個種子。NewKeyFromSeed 從種子還原完整私鑰,Seed 取回種子。
只需要保存 32 位元組的種子,就能在任何時候重建同一把金鑰。範例使用 RFC 8032 的公開測試向量,所以每次執行的公鑰都一樣。
簽名:
  1. func NewKeyFromSeed(seed []byte) PrivateKey
  2. func (priv PrivateKey) Seed() []byte

範例:
  1. package main
  2. import (
  3. "crypto/ed25519"
  4. "encoding/hex"
  5. "fmt"
  6. )
  7. func main() {
  8. seed, err := hex.DecodeString("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
  9. if err != nil {
  10. fmt.Println("error:", err)
  11. return
  12. }
  13. priv := ed25519.NewKeyFromSeed(seed)
  14. pub := priv.Public().(ed25519.PublicKey)
  15. fmt.Println("公鑰:", hex.EncodeToString(pub))
  16. fmt.Println("Seed 還原相同:", string(priv.Seed()) == string(seed))
  17. }

輸出:
  1. 公鑰: d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a
  2. Seed 還原相同: true

注意:種子長度不是 32 位元組時 NewKeyFromSeed 會 panic。範例中的種子是公開的測試值,正式環境的種子必須由安全亂數產生並妥善保密。

Sign


用私鑰對訊息簽章,回傳 64 位元組的簽章。直接傳原始訊息即可,不需要先雜湊。Ed25519 是確定性的:同一把金鑰簽同一訊息,結果永遠相同。
簽名:
  1. func Sign(privateKey PrivateKey, message []byte) []byte

範例:
  1. package main
  2. import (
  3. "crypto/ed25519"
  4. "encoding/hex"
  5. "fmt"
  6. )
  7. func main() {
  8. seed, _ := hex.DecodeString("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
  9. priv := ed25519.NewKeyFromSeed(seed)
  10. sig := ed25519.Sign(priv, []byte("hello, gopher"))
  11. sig2 := ed25519.Sign(priv, []byte("hello, gopher"))
  12. fmt.Println("簽章長度:", len(sig))
  13. fmt.Println("兩次簽章相同:", string(sig) == string(sig2))
  14. fmt.Println("簽章前 16 字元:", hex.EncodeToString(sig)[:16])
  15. }

輸出:
  1. 簽章長度: 64
  2. 兩次簽章相同: true
  3. 簽章前 16 字元: 3b5eb0131bd43ec8

注意:私鑰長度不是 PrivateKeySize(64)時會 panic。從外部讀入的金鑰要先檢查長度。

Verify


用公鑰驗證簽章,回傳 bool。訊息被改、簽章被改、甚至簽章長度不對,都只會得到 false。
簽名:
  1. func Verify(publicKey PublicKey, message, sig []byte) bool

範例:
  1. package main
  2. import (
  3. "crypto/ed25519"
  4. "crypto/rand"
  5. "fmt"
  6. )
  7. func main() {
  8. pub, priv, err := ed25519.GenerateKey(rand.Reader)
  9. if err != nil {
  10. fmt.Println("error:", err)
  11. return
  12. }
  13. msg := []byte(`{"user":"alice","role":"viewer"}`)
  14. sig := ed25519.Sign(priv, msg)
  15. fmt.Println("原訊息:", ed25519.Verify(pub, msg, sig))
  16. fmt.Println("竄改後:", ed25519.Verify(pub, []byte(`{"user":"alice","role":"admin"}`), sig))
  17. fmt.Println("簽章長度錯誤:", ed25519.Verify(pub, msg, sig[:10]))
  18. }

輸出:
  1. 原訊息: true
  2. 竄改後: false
  3. 簽章長度錯誤: false

注意:公鑰長度不是 PublicKeySize(32)時 Verify 會 panic,而不是回傳 false。

PrivateKey.Sign(crypto.Signer 介面)


ed25519.PrivateKey 實作 crypto 的 crypto.Signer 介面,所以可以和 RSA、ECDSA 金鑰一起放進接收 crypto.Signer 的程式(例如 x509.CreateCertificate)。
和其他演算法不同的是:這裡傳入的是原始訊息,不是雜湊值;opts 傳 crypto.Hash(0) 表示一般的 Ed25519。rand 參數不會被使用,可傳 nil。
簽名:
  1. func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error)

範例:
  1. package main
  2. import (
  3. "crypto"
  4. "crypto/ed25519"
  5. "crypto/rand"
  6. "fmt"
  7. )
  8. func main() {
  9. pub, priv, err := ed25519.GenerateKey(rand.Reader)
  10. if err != nil {
  11. fmt.Println("error:", err)
  12. return
  13. }
  14. var signer crypto.Signer = priv
  15. msg := []byte("deploy production")
  16. sig, err := signer.Sign(nil, msg, crypto.Hash(0))
  17. if err != nil {
  18. fmt.Println("error:", err)
  19. return
  20. }
  21. fmt.Println("驗證通過:", ed25519.Verify(pub, msg, sig))
  22. fmt.Println("Public() 相同:", pub.Equal(signer.Public()))
  23. }

輸出:
  1. 驗證通過: true
  2. Public() 相同: true

Options 與 VerifyWithOptions


Options 用來選擇 Ed25519 的變體:
設定變體用途
Hash: 0、Context: ""Ed25519一般情況
Hash: 0、Context 非空Ed25519ctx用 context 字串區分用途,避免 A 用途的簽章被拿去 B 用途冒用
Hash: crypto.SHA512Ed25519ph先雜湊再簽,傳入的是 SHA-512 雜湊值

簽章用 PrivateKey.Sign 帶入 *Options,驗證用 VerifyWithOptions,失敗時回傳錯誤。Context 最長 255 位元組。
簽名:
  1. func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error

範例:
  1. package main
  2. import (
  3. "crypto/ed25519"
  4. "crypto/rand"
  5. "fmt"
  6. )
  7. func main() {
  8. pub, priv, err := ed25519.GenerateKey(rand.Reader)
  9. if err != nil {
  10. fmt.Println("error:", err)
  11. return
  12. }
  13. msg := []byte("amount=500")
  14. opts := &ed25519.Options{Context: "payments-v1"}
  15. sig, err := priv.Sign(nil, msg, opts)
  16. if err != nil {
  17. fmt.Println("error:", err)
  18. return
  19. }
  20. err = ed25519.VerifyWithOptions(pub, msg, sig, opts)
  21. fmt.Println("相同 context:", err == nil)
  22. err = ed25519.VerifyWithOptions(pub, msg, sig, &ed25519.Options{Context: "refunds-v1"})
  23. fmt.Println("不同 context:", err)
  24. fmt.Println("用一般 Verify:", ed25519.Verify(pub, msg, sig))
  25. }

輸出:
  1. 相同 context: true
  2. 不同 context: ed25519: invalid signature
  3. 用一般 Verify: false

注意:簽章與驗證兩端的 Options 必須完全一致;用了 context 的簽章,以一般 Verify 驗證也會失敗。

重點整理


  • Ed25519 公鑰 32 位元組、簽章固定 64 位元組,新系統做簽章優先選它
  • Sign 直接接收原始訊息,不需要先雜湊;結果是確定性的
  • 只要保存 32 位元組的種子,就能用 NewKeyFromSeed 重建私鑰
  • 金鑰長度不對時 Sign、Verify 會 panic,外部輸入要先檢查長度
  • 需要區分簽章用途時,用 Options.Context(Ed25519ctx)搭配 VerifyWithOptions

資料來源