← 中文资源

简体中文版本

ECDH 共享密钥协商

用 crypto/ecdh 的 P-256 密钥协商共享密钥:双方交换公钥后得到完全相同的字节,第三方用别的私钥则无法复现。

阅读英文原文

实现说明

ECDH 共享密钥协商以函数 main为骨架。 错误处理是内联的:6 处测试 err != nil 并立即分支。

使用要点

  • 每一步打印都带着自己的标签:alice key failed:、bob key failed:、alice ecdh failed:。

常见问题

运行「ECDH 共享密钥协商」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 alice key failed:、bob key failed:、alice ecdh failed: 标签标明各步骤。

核心语句

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
}

代码示例

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))
}