Self Signed Certificate Create And Parse
Generate an ECDSA key, issue a self-signed certificate with CreateCertificate, parse the DER back with ParseCertificate, and encode it as PEM.
Code
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"time"
)
func main() {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
panic(err)
}
// self-signed: issuer == subject, one key signs and holds
template := &x509.Certificate{
SerialNumber: big.NewInt(2026),
Subject: pkix.Name{CommonName: "demo.internal", Organization: []string{"Example Corp"}},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: true,
DNSNames: []string{"demo.internal"},
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
panic(err)
}
parsed, err := x509.ParseCertificate(der)
if err != nil {
panic(err)
}
fmt.Println("subject:", parsed.Subject.CommonName)
fmt.Println("issuer:", parsed.Issuer.CommonName)
fmt.Println("serial:", parsed.SerialNumber)
fmt.Println("dns names:", parsed.DNSNames)
fmt.Println("is CA:", parsed.IsCA)
block := &pem.Block{Type: "CERTIFICATE", Bytes: der}
fmt.Println("pem first line:", string(pem.EncodeToMemory(block))[:27])
}What the demo mints
An ECDSA P-256 key is generated from crypto/rand, then a template certificate is signed with that same key: issuer and subject are identical, which is the definition of self-signed. Serial 2026, a one-day validity window starting an hour ago, and the DNS name demo.internal all come from the template.
CreateCertificate returns DER bytes; ParseCertificate decodes them back into fields, and the prints show subject, issuer, serial, DNS names and IsCA true. The last line encodes the DER as PEM and prints the first 27 bytes, the —–BEGIN CERTIFICATE prefix.
Points worth noting
- KeyUsage combines DigitalSignature with CertSign because the cert is its own CA.
- NotBefore is backdated an hour to survive clock skew.
Interactive Tools for This Topic
FAQ
- What makes the certificate self-signed here?
- CreateCertificate receives the same template as parent and the private key as signer, so issuer equals subject and one key both signs and holds the certificate.
Report a problem with this exampleOpens a pre-filled issue on GitHub.