Standard library / crypto/x509

crypto/x509.SystemCertPool()

Returns a copy of system trust roots if available. On Linux this standalone example overrides SSL_CERT_FILE and SSL_CERT_DIR only in its own process, loads a synthetic CA from a temporary file, and checks a synthetic chain. In applications do not change process-wide trust configuration casually; platform behavior differs. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func SystemCertPool() (*CertPool, error)

Return Value

(*CertPool, error)

Result as described above; check any returned error before use.

Working Example

Example Snippetgo
package main
import (  "crypto/ed25519"  "crypto/rand"  "crypto/x509"  "crypto/x509/pkix"  "encoding/pem"  "fmt"  "math/big"  "os"  "path/filepath"  "time")
func main() {  root, leaf, key, now := fixture()  _, _, _, _ = root, leaf, key, now  dir := must(os.MkdirTemp("", "bytemind-pki-"))  defer os.RemoveAll(dir)  file := filepath.Join(dir, "root.pem")  check(os.WriteFile(file, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw}), 0600))  check(os.Setenv("SSL_CERT_FILE", file))  check(os.Setenv("SSL_CERT_DIR", dir))  pool := must(x509.SystemCertPool())  _, e := leaf.Verify(x509.VerifyOptions{Roots: pool, DNSName: "example.invalid", CurrentTime: now})  fmt.Println(e == nil)}
// Fixture: ephemeral Ed25519 keys, synthetic names and fixed verification time.func fixture() (*x509.Certificate, *x509.Certificate, ed25519.PrivateKey, time.Time) {  now := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)  pub, key, e := ed25519.GenerateKey(rand.Reader)  check(e)  ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Demo CA"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), BasicConstraintsValid: true, IsCA: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, SubjectKeyId: []byte{1, 2, 3}}  root := must(x509.ParseCertificate(must(x509.CreateCertificate(rand.Reader, ca, ca, pub, key))))  leafPub, _, e := ed25519.GenerateKey(rand.Reader)  check(e)  t := &x509.Certificate{SerialNumber: big.NewInt(2), DNSNames: []string{"example.invalid"}, NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}  leaf := must(x509.ParseCertificate(must(x509.CreateCertificate(rand.Reader, t, root, leafPub, key))))  return root, leaf, key, now}
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)  }}
Go Reference