Skip to content

Instantly share code, notes, and snippets.

@gitsrc
Created May 2, 2019 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitsrc/bb66050a7bc420e6af251d815d6e5228 to your computer and use it in GitHub Desktop.
Save gitsrc/bb66050a7bc420e6af251d815d6e5228 to your computer and use it in GitHub Desktop.
golang_ecdh_X25519
package main
import (
"bytes"
"crypto/rand"
"fmt"
"github.com/aead/ecdh"
"log"
)
func main(){
c25519 := ecdh.X25519()
//private 是 随机io里面的32byte数据:产生alice的 私钥 和 公钥
//A 端生成 本地公钥 和 私钥
privateAlice, publicAlice, err := c25519.GenerateKey(rand.Reader)
if err != nil {
fmt.Printf("Failed to generate Alice's private/public key pair: %s\n", err)
}
//B 段生成 本地公钥 和 私钥
privateBob, publicBob, err := c25519.GenerateKey(rand.Reader)
if err != nil {
fmt.Printf("Failed to generate Bob's private/public key pair: %s\n", err)
}
// 相互交换A 和 B 端的公钥
//A端 检测B的公钥 并根据B端公钥 和自己的私钥 生成 最终协商秘钥
if err := c25519.Check(publicBob); err != nil {
fmt.Printf("Bob's public key is not on the curve: %s\n", err)
}
secretAlice := c25519.ComputeSecret(privateAlice, publicBob)
//B端 检测A的公钥 并根据A端公钥 和自己的私钥 生成 最终协商秘钥
if err := c25519.Check(publicAlice); err != nil {
fmt.Printf("Alice's public key is not on the curve: %s\n", err)
}
secretBob := c25519.ComputeSecret(privateBob, publicAlice)
if !bytes.Equal(secretAlice, secretBob) {
fmt.Printf("key exchange failed - secret X coordinates not equal\n")
}
log.Println(secretAlice ,len(secretAlice))
log.Println(secretBob , len(secretBob))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment