How to Parse and Generate X.509 Certificates in Go

Parse X.509 certificates with x509.ParseCertificate and generate them using x509.CreateCertificate in Go.

Use the crypto/x509 package to parse certificates with x509.ParseCertificate and generate them by creating a x509.Certificate struct, signing it with x509.CreateCertificate, and encoding the result with x509.MarshalPKIXPublicKey or x509.MarshalPKCS1PrivateKey.

package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math/big"
	"time"
)

func main() {
	// Generate private key
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		panic(err)
	}

	// Define certificate template
	template := x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			Organization: []string{"My Org"},
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(365 * 24 * time.Hour),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		BasicConstraintsValid: true,
	}

	// Generate certificate
	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		panic(err)
	}

	// Encode certificate to PEM
	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	fmt.Println(string(certPEM))

	// Parse certificate
	cert, err := x509.ParseCertificate(derBytes)
	if err != nil {
		panic(err)
	}
	fmt.Println("Subject:", cert.Subject.Organization)
}