ecdsa.com

Generate a key pair · Go

How to generate an ECDSA key pair in Go

Go generates an ECDSA key pair with the standard library in one call to ecdsa.GenerateKey — the rest of the recipe is serialization: PKCS#8 DER for the private key, SPKI (PKIX) for the public key, both wrapped in PEM.

Tested with Go 1.26 (standard library only).

generate_key.go — P-256 pair, PEM files
package main
 
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"os"
)
 
func main() {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
panic(err)
}
 
privDer, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
panic(err)
}
pubDer, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
if err != nil {
panic(err)
}
 
os.WriteFile("key.pem", pem.EncodeToMemory(
&pem.Block{Type: "PRIVATE KEY", Bytes: privDer}), 0o600)
os.WriteFile("pub.pem", pem.EncodeToMemory(
&pem.Block{Type: "PUBLIC KEY", Bytes: pubDer}), 0o644)
}

How it works

  1. elliptic.P256() (and P384(), P521()) are the NIST curves in the standard library; all use constant-time implementations.
  2. MarshalPKCS8PrivateKey produces the modern container; MarshalECPrivateKey exists for the legacy SEC1 layout other tools may demand.
  3. PEM block types matter: PRIVATE KEY for PKCS#8, EC PRIVATE KEY for SEC1, PUBLIC KEY for SPKI. Wrong label, failed parse elsewhere.
  4. 0o600 on the private key file is not optional hygiene — ssh-style tooling actively rejects world-readable keys.

Gotchas

  • secp256k1 is not in the Go standard library — elliptic.P256() is NIST P-256. For Bitcoin/Ethereum work use a dedicated package (e.g. dcrd's secp256k1) rather than forcing stdlib types.
  • Mismatched marshal/parse pairs are a classic: MarshalPKCS8PrivateKey output must be read with ParsePKCS8PrivateKey, SEC1 output with ParseECPrivateKey. The PEM label tells you which you have.
  • Always rand.Reader for generation. Seeding anything deterministic "for tests" and letting it leak to production is how private keys end up recoverable.

Related recipes