Standard library / crypto/ecdh
crypto/ecdh.PrivateKey.ECDH()
Computes shared secret with peer key on same curve; X25519 all-zero output and mismatched curves fail. Use authenticated key exchange and protocol-specific KDF; never use raw output directly as an encryption key. Expected stdout: 'true\n'.
Formal Syntax & Structure
go syntaxgo
func (k *PrivateKey) ECDH(remote *PublicKey) ([]byte, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| remote | *PublicKey | Peer public key on the same curve. |
Return Value
([]byte, error)
Result as described above; check any returned error before use.
Working Example
Example Snippetgo
package main
import ( "bytes" "crypto/ecdh" "crypto/rand" "fmt")
func main() { k := must(ecdh.X25519().GenerateKey(rand.Reader)) peer := must(ecdh.X25519().GenerateKey(rand.Reader)) s := must(k.ECDH(peer.PublicKey())) t := must(peer.ECDH(k.PublicKey())) fmt.Println(bytes.Equal(s, t))}func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}