How to Generate Self-Signed Certificates in Go

Generate a self-signed certificate in Go using crypto/x509 and crypto/rand packages.

Use the crypto/x509 and crypto/rand packages to generate a private key and a self-signed certificate in memory.

package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"math/big"
	"time"
)

func main() {
	priv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	notBefore := time.Now()
	notAfter := notBefore.Add(365 * 24 * time.Hour)

	template := x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			Organization: []string{"My Org"},
		},
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)

	privPEM := &pem.Block{Type: "EC PRIVATE KEY", Bytes: x509.MarshalECPrivateKey(priv)}
	certPEM := &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}

	pem.Encode(os.Stdout, privPEM)
	pem.Encode(os.Stdout, certPEM)
}

Note: Add "os" to imports if writing to stdout.