crypto/ed25519
最後更新
crypto/ed25519 實作 Ed25519 數位簽章:金鑰短、速度快、API 簡單,是新系統做簽章的首選。這個套件做什麼
數位簽章(digital signature)讓接收方確認「資料是誰送的、途中有沒有被改」。簽署者用私鑰(private key)簽章,任何人用公鑰(public key)驗證。
Ed25519 是建立在 Curve25519 橢圓曲線上的簽章演算法(RFC 8032)。和 crypto/ecdsa、crypto/rsa 比起來,它有幾個對新手友善的特性:
| 特性 | Ed25519 | ECDSA P-256 | RSA 2048 |
|---|---|---|---|
| 公鑰長度 | 32 位元組 | 65 位元組(未壓縮) | 約 270 位元組(DER) |
| 簽章長度 | 固定 64 位元組 | 不固定,最長 72 | 256 位元組 |
| 簽章前要自己雜湊嗎 | 不用,直接傳原始訊息 | 要 | 要 |
| 同一訊息簽兩次 | 結果相同(確定性) | 預設不同 | PSS 不同 |
什麼時候用:
- 自己設計的 API 簽章、Webhook 驗證、軟體發佈簽章
- SSH 金鑰(
ssh-ed25519)、JWT 的 EdDSA
什麼時候不用:對方系統只接受 RSA 或 NIST 曲線(例如某些 FIPS 環境),就改用
crypto/rsa 或 crypto/ecdsa。金鑰型別
PublicKey、PrivateKey 本質上都是 []byte,可以直接存取長度、轉成十六進位。要存成 PEM 檔,用 crypto/x509 的 MarshalPKCS8PrivateKey/MarshalPKIXPublicKey。匯入
- import "crypto/ed25519"
常用 API
GenerateKey
產生一組新的公鑰與私鑰。
random 傳 nil 時使用安全的系統亂數;慣例也可傳 crypto/rand 的 rand.Reader。套件提供四個長度常數:
PublicKeySize(32)、PrivateKeySize(64)、SignatureSize(64)、SeedSize(32)。簽名:
- func GenerateKey(random io.Reader) (PublicKey, PrivateKey, error)
範例:
- package main
- import (
- "crypto/ed25519"
- "crypto/rand"
- "fmt"
- )
- func main() {
- pub, priv, err := ed25519.GenerateKey(rand.Reader)
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Println("公鑰長度:", len(pub), "PublicKeySize =", ed25519.PublicKeySize)
- fmt.Println("私鑰長度:", len(priv), "PrivateKeySize =", ed25519.PrivateKeySize)
- fmt.Println("種子長度:", len(priv.Seed()), "SeedSize =", ed25519.SeedSize)
- }
輸出:
- 公鑰長度: 32 PublicKeySize = 32
- 私鑰長度: 64 PrivateKeySize = 64
- 種子長度: 32 SeedSize = 32
每次執行金鑰都不同,所以這裡只印長度。
NewKeyFromSeed 與 PrivateKey.Seed
Ed25519 的私鑰其實可以完全由一個 32 位元組的「種子(seed)」推導出來,RFC 8032 所說的私鑰就是這個種子。
NewKeyFromSeed 從種子還原完整私鑰,Seed 取回種子。只需要保存 32 位元組的種子,就能在任何時候重建同一把金鑰。範例使用 RFC 8032 的公開測試向量,所以每次執行的公鑰都一樣。
簽名:
- func NewKeyFromSeed(seed []byte) PrivateKey
- func (priv PrivateKey) Seed() []byte
範例:
- package main
- import (
- "crypto/ed25519"
- "encoding/hex"
- "fmt"
- )
- func main() {
- seed, err := hex.DecodeString("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- priv := ed25519.NewKeyFromSeed(seed)
- pub := priv.Public().(ed25519.PublicKey)
- fmt.Println("公鑰:", hex.EncodeToString(pub))
- fmt.Println("Seed 還原相同:", string(priv.Seed()) == string(seed))
- }
輸出:
- 公鑰: d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a
- Seed 還原相同: true
注意:種子長度不是 32 位元組時
NewKeyFromSeed 會 panic。範例中的種子是公開的測試值,正式環境的種子必須由安全亂數產生並妥善保密。Sign
用私鑰對訊息簽章,回傳 64 位元組的簽章。直接傳原始訊息即可,不需要先雜湊。Ed25519 是確定性的:同一把金鑰簽同一訊息,結果永遠相同。
簽名:
- func Sign(privateKey PrivateKey, message []byte) []byte
範例:
- package main
- import (
- "crypto/ed25519"
- "encoding/hex"
- "fmt"
- )
- func main() {
- seed, _ := hex.DecodeString("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
- priv := ed25519.NewKeyFromSeed(seed)
- sig := ed25519.Sign(priv, []byte("hello, gopher"))
- sig2 := ed25519.Sign(priv, []byte("hello, gopher"))
- fmt.Println("簽章長度:", len(sig))
- fmt.Println("兩次簽章相同:", string(sig) == string(sig2))
- fmt.Println("簽章前 16 字元:", hex.EncodeToString(sig)[:16])
- }
輸出:
- 簽章長度: 64
- 兩次簽章相同: true
- 簽章前 16 字元: 3b5eb0131bd43ec8
注意:私鑰長度不是
PrivateKeySize(64)時會 panic。從外部讀入的金鑰要先檢查長度。Verify
用公鑰驗證簽章,回傳
bool。訊息被改、簽章被改、甚至簽章長度不對,都只會得到 false。簽名:
- func Verify(publicKey PublicKey, message, sig []byte) bool
範例:
- package main
- import (
- "crypto/ed25519"
- "crypto/rand"
- "fmt"
- )
- func main() {
- pub, priv, err := ed25519.GenerateKey(rand.Reader)
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- msg := []byte(`{"user":"alice","role":"viewer"}`)
- sig := ed25519.Sign(priv, msg)
- fmt.Println("原訊息:", ed25519.Verify(pub, msg, sig))
- fmt.Println("竄改後:", ed25519.Verify(pub, []byte(`{"user":"alice","role":"admin"}`), sig))
- fmt.Println("簽章長度錯誤:", ed25519.Verify(pub, msg, sig[:10]))
- }
輸出:
- 原訊息: true
- 竄改後: false
- 簽章長度錯誤: 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。簽名:
- func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error)
範例:
- package main
- import (
- "crypto"
- "crypto/ed25519"
- "crypto/rand"
- "fmt"
- )
- func main() {
- pub, priv, err := ed25519.GenerateKey(rand.Reader)
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- var signer crypto.Signer = priv
- msg := []byte("deploy production")
- sig, err := signer.Sign(nil, msg, crypto.Hash(0))
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Println("驗證通過:", ed25519.Verify(pub, msg, sig))
- fmt.Println("Public() 相同:", pub.Equal(signer.Public()))
- }
輸出:
- 驗證通過: true
- Public() 相同: true
Options 與 VerifyWithOptions
Options 用來選擇 Ed25519 的變體:| 設定 | 變體 | 用途 |
|---|---|---|
Hash: 0、Context: "" | Ed25519 | 一般情況 |
Hash: 0、Context 非空 | Ed25519ctx | 用 context 字串區分用途,避免 A 用途的簽章被拿去 B 用途冒用 |
Hash: crypto.SHA512 | Ed25519ph | 先雜湊再簽,傳入的是 SHA-512 雜湊值 |
簽章用
PrivateKey.Sign 帶入 *Options,驗證用 VerifyWithOptions,失敗時回傳錯誤。Context 最長 255 位元組。簽名:
- func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error
範例:
- package main
- import (
- "crypto/ed25519"
- "crypto/rand"
- "fmt"
- )
- func main() {
- pub, priv, err := ed25519.GenerateKey(rand.Reader)
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- msg := []byte("amount=500")
- opts := &ed25519.Options{Context: "payments-v1"}
- sig, err := priv.Sign(nil, msg, opts)
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- err = ed25519.VerifyWithOptions(pub, msg, sig, opts)
- fmt.Println("相同 context:", err == nil)
- err = ed25519.VerifyWithOptions(pub, msg, sig, &ed25519.Options{Context: "refunds-v1"})
- fmt.Println("不同 context:", err)
- fmt.Println("用一般 Verify:", ed25519.Verify(pub, msg, sig))
- }
輸出:
- 相同 context: true
- 不同 context: ed25519: invalid signature
- 用一般 Verify: false
注意:簽章與驗證兩端的
Options 必須完全一致;用了 context 的簽章,以一般 Verify 驗證也會失敗。重點整理
- Ed25519 公鑰 32 位元組、簽章固定 64 位元組,新系統做簽章優先選它
Sign直接接收原始訊息,不需要先雜湊;結果是確定性的- 只要保存 32 位元組的種子,就能用
NewKeyFromSeed重建私鑰 - 金鑰長度不對時
Sign、Verify會 panic,外部輸入要先檢查長度 - 需要區分簽章用途時,用
Options.Context(Ed25519ctx)搭配VerifyWithOptions