// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Generate a self-signed X.509 certificate for a TLS server. Outputs to // 'cert.pem' and 'key.pem' and will overwrite existing files. package crypt import ( "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "log" "math/big" "net" "strings" "time" ) type GenerateCertificate struct { Organization string Host string ValidFrom string ValidFor time.Duration IsCA bool RSABits int EcdsaCurve string Ed25519Key bool } func (gc *GenerateCertificate) publicKey(priv interface{}) interface{} { switch k := priv.(type) { case *rsa.PrivateKey: return &k.PublicKey case *ecdsa.PrivateKey: return &k.PublicKey case ed25519.PrivateKey: return k.Public().(ed25519.PublicKey) default: return nil } } func (gc *GenerateCertificate) GenerateTLSConfig() (*tls.Config, error) { var priv interface{} var err error switch gc.EcdsaCurve { case "": if gc.Ed25519Key { _, priv, err = ed25519.GenerateKey(rand.Reader) } else { priv, err = rsa.GenerateKey(rand.Reader, gc.RSABits) } case "P224": priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader) case "P256": priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) case "P384": priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) case "P521": priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) default: log.Fatalf("Unrecognized elliptic curve: %q", gc.EcdsaCurve) return nil, err } if err != nil { log.Fatalf("Failed to generate private key: %v", err) return nil, err } var notBefore time.Time if len(gc.ValidFrom) == 0 { notBefore = time.Now() } else { notBefore, err = time.Parse("Jan 2 15:04:05 2006", gc.ValidFrom) if err != nil { log.Fatalf("Failed to parse creation date: %v", err) return nil, err } } notAfter := notBefore.Add(gc.ValidFor) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { log.Fatalf("Failed to generate serial number: %v", err) return nil, err } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{gc.Organization}, }, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, } hosts := strings.Split(gc.Host, ",") for _, h := range hosts { if ip := net.ParseIP(h); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, h) } } if gc.IsCA { template.IsCA = true template.KeyUsage |= x509.KeyUsageCertSign } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, gc.publicKey(priv), priv) if err != nil { log.Fatalf("Failed to create certificate: %v", err) return nil, err } privBytes, err := x509.MarshalPKCS8PrivateKey(priv) if err != nil { log.Fatalf("Unable to marshal private key: %v", err) return nil, err } keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) tlsCert, err := tls.X509KeyPair(certPEM, keyPEM) return &tls.Config{Certificates: []tls.Certificate{tlsCert}}, nil }