func newRootCert()

in testing/certutil/certutil.go [331:401]


func newRootCert(priv crypto.PrivateKey, pub crypto.PublicKey, opts ...Option) (*x509.Certificate, Pair, error) {
	cn := "High Council"
	cfg := getCgf(opts)
	if cfg.cnPrefix != "" {
		cn = fmt.Sprintf("[%s] %s", cfg.cnPrefix, cn)
	}
	notBefore, notAfter := makeNotBeforeAndAfter()

	rootTemplate := x509.Certificate{
		SerialNumber: big.NewInt(1653),
		Subject: pkix.Name{
			Country:            []string{"Gallifrey"},
			Locality:           []string{"The Capitol"},
			OrganizationalUnit: []string{"Time Lords"},
			Organization:       []string{"High Council of the Time Lords"},
			CommonName:         cn,
		},
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
		SubjectKeyId:          generateSubjectKeyID(pub),
	}

	rootCertRawBytes, err := x509.CreateCertificate(
		rand.Reader, &rootTemplate, &rootTemplate, pub, priv)
	if err != nil {
		return nil, Pair{}, fmt.Errorf("could not create CA: %w", err)
	}

	rootPrivKeyDER, err := x509.MarshalPKCS8PrivateKey(priv)
	if err != nil {
		return nil, Pair{}, fmt.Errorf("could not marshal private key: %w", err)
	}

	// PEM private key
	var rootPrivBytesOut []byte
	rootPrivateKeyBuff := bytes.NewBuffer(rootPrivBytesOut)
	err = pem.Encode(rootPrivateKeyBuff,
		&pem.Block{Type: keyBlockType(priv), Bytes: rootPrivKeyDER})
	if err != nil {
		return nil, Pair{}, fmt.Errorf("could not pem.Encode private key: %w", err)
	}

	// PEM certificate
	var rootCertBytesOut []byte
	rootCertPemBuff := bytes.NewBuffer(rootCertBytesOut)
	err = pem.Encode(rootCertPemBuff,
		&pem.Block{Type: "CERTIFICATE", Bytes: rootCertRawBytes})
	if err != nil {
		return nil, Pair{}, fmt.Errorf("could not pem.Encode certificate: %w", err)
	}

	// tls.Certificate
	rootTLSCert, err := tls.X509KeyPair(
		rootCertPemBuff.Bytes(), rootPrivateKeyBuff.Bytes())
	if err != nil {
		return nil, Pair{}, fmt.Errorf("could not create key pair: %w", err)
	}

	rootCACert, err := x509.ParseCertificate(rootTLSCert.Certificate[0])
	if err != nil {
		return nil, Pair{}, fmt.Errorf("could not parse certificate: %w", err)
	}

	return rootCACert, Pair{
		Cert: rootCertPemBuff.Bytes(),
		Key:  rootPrivateKeyBuff.Bytes(),
	}, nil
}