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.

GoSecurity Boundaries

Code

gosnippet
53 lines
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

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:`.