~/snippets/go-new-public-private-certificate
Published on

Generate Public/Private Certificate

392 words2 min read
// generateCert generates a new public/private key pair and returns them
func generateCert(bits int) (*x509.Certificate, *rsa.PrivateKey, error) {
	privKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, nil, err
	}

	limit := new(big.Int).Lsh(big.NewInt(1), 128)

	sn, err := rand.Int(rand.Reader, limit)
	if err != nil {
		return nil, nil, err
	}

	tmpl := &x509.Certificate{
		SerialNumber:          sn,
		Subject:               pkix.Name{Organization: []string{"Wibble Wobble, Inc."}},
		SignatureAlgorithm:    x509.SHA256WithRSA,
		NotBefore:             time.Now(),
		NotAfter:              time.Now().AddDate(1, 0, 0),
		BasicConstraintsValid: true,
	}

	certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &privKey.PublicKey, privKey)
	if err != nil {
		return nil, nil, err
	}

	x509PubCert, err := x509.ParseCertificate(certDER)
	if err != nil {
		return nil, nil, err
	}

    // Alternatively, you can pem encode
    // p := &pem.Block{
	// 	Type:  "CERTIFICATE",
	// 	Bytes: certDER,
	// }
    //
    // b := pem.EncodeToMemory(p)
    // fmt.Println(string(b)) // will return string representation of certificate (i.e. -----BEGIN CERTIFICATE-----)

	return x509PubCert, privKey, nil
}