ECDH Shared Secret Exchange
Agree on an identical secret with crypto/ecdh P-256 keys, compare both sides, and confirm an eavesdropper derives a different value.
Code
package main
import (
"bytes"
"crypto/ecdh"
"crypto/rand"
"encoding/hex"
"fmt"
)
func main() {
curve := ecdh.P256()
// 双方各自生成一对临时密钥
alice, err := curve.GenerateKey(rand.Reader)
if err != nil {
fmt.Println("alice key failed:", err)
return
}
bob, err := curve.GenerateKey(rand.Reader)
if err != nil {
fmt.Println("bob key failed:", err)
return
}
// 交换公钥后各自计算共享密钥
aliceSecret, err := alice.ECDH(bob.PublicKey())
if err != nil {
fmt.Println("alice ecdh failed:", err)
return
}
bobSecret, err := bob.ECDH(alice.PublicKey())
if err != nil {
fmt.Println("bob ecdh failed:", err)
return
}
fmt.Println("secret bytes:", len(aliceSecret))
fmt.Println("hex:", hex.EncodeToString(aliceSecret))
fmt.Println("both sides agree:", bytes.Equal(aliceSecret, bobSecret))
// 第三方只用自己的私钥与 Alice 公钥,得到不同结果
mallory, err := curve.GenerateKey(rand.Reader)
if err != nil {
fmt.Println("mallory key failed:", err)
return
}
mallorySecret, err := mallory.ECDH(alice.PublicKey())
if err != nil {
fmt.Println("mallory ecdh failed:", err)
return
}
fmt.Println("eavesdropper differs:", !bytes.Equal(mallorySecret, aliceSecret))
}What the code does
ECDH Shared Secret Exchange is built around the function main.
Error handling is inline: 6 places test err != nil and branch immediately.
Applying it
The run emits 10 labeled sections — alice key failed:, bob key failed:, alice ecdh failed:, bob ecdh failed:, secret bytes:, hex:, both sides agree:, mallory key failed:, mallory ecdh failed:, eavesdropper differs: — one per step.
Statements that carry the weight
if err != nil {
fmt.Println("alice key failed:", err)
return
}
if err != nil {
fmt.Println("bob key failed:", err)
return
}
if err != nil {
fmt.Println("alice ecdh failed:", err)
return
}
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- What does ECDH Shared Secret Exchange print when run?
- Run it as a complete program — the output lines carry labels such as `alice key failed:`, `bob key failed:`, `alice ecdh failed:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.