|
| 1 | +// Copyright 2009 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +// Generate a self-signed X.509 certificate for a TLS server. Outputs to |
| 6 | +// 'cert.pem' and 'key.pem' and will overwrite existing files. |
| 7 | + |
| 8 | +package main |
| 9 | + |
| 10 | +import ( |
| 11 | + "crypto/ecdsa" |
| 12 | + "crypto/ed25519" |
| 13 | + "crypto/elliptic" |
| 14 | + "crypto/rand" |
| 15 | + "crypto/rsa" |
| 16 | + "crypto/x509" |
| 17 | + "crypto/x509/pkix" |
| 18 | + "encoding/pem" |
| 19 | + "flag" |
| 20 | + "fmt" |
| 21 | + "math/big" |
| 22 | + "net" |
| 23 | + "os" |
| 24 | + "strings" |
| 25 | + "time" |
| 26 | +) |
| 27 | + |
| 28 | +var ( |
| 29 | + validFrom = flag.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011") |
| 30 | + validFor = flag.Duration("duration", 5*time.Hour, "Duration that certificate is valid for") |
| 31 | + isCA = flag.Bool("ca", false, "whether this cert should be its own Certificate Authority") |
| 32 | + rsaBits = flag.Int("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set") |
| 33 | + ecdsaCurve = flag.String("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P521") |
| 34 | + ed25519Key = flag.Bool("ed25519", false, "Generate an Ed25519 key") |
| 35 | +) |
| 36 | + |
| 37 | +func publicKey(priv interface{}) interface{} { |
| 38 | + switch k := priv.(type) { |
| 39 | + case *rsa.PrivateKey: |
| 40 | + return &k.PublicKey |
| 41 | + case *ecdsa.PrivateKey: |
| 42 | + return &k.PublicKey |
| 43 | + case ed25519.PrivateKey: |
| 44 | + return k.Public().(ed25519.PublicKey) |
| 45 | + default: |
| 46 | + return nil |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func generateCertificate(host string) error { |
| 51 | + if len(host) == 0 { |
| 52 | + return fmt.Errorf("Missing required --host parameter") |
| 53 | + } |
| 54 | + |
| 55 | + var priv interface{} |
| 56 | + var err error |
| 57 | + switch *ecdsaCurve { |
| 58 | + case "": |
| 59 | + if *ed25519Key { |
| 60 | + _, priv, err = ed25519.GenerateKey(rand.Reader) |
| 61 | + } else { |
| 62 | + priv, err = rsa.GenerateKey(rand.Reader, *rsaBits) |
| 63 | + } |
| 64 | + case "P224": |
| 65 | + priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader) |
| 66 | + case "P256": |
| 67 | + priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 68 | + case "P384": |
| 69 | + priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) |
| 70 | + case "P521": |
| 71 | + priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) |
| 72 | + default: |
| 73 | + return fmt.Errorf("Unrecognized elliptic curve: %q", *ecdsaCurve) |
| 74 | + } |
| 75 | + if err != nil { |
| 76 | + return fmt.Errorf("Failed to generate private key: %v", err) |
| 77 | + } |
| 78 | + |
| 79 | + // ECDSA, ED25519 and RSA subject keys should have the DigitalSignature |
| 80 | + // KeyUsage bits set in the x509.Certificate template |
| 81 | + keyUsage := x509.KeyUsageDigitalSignature |
| 82 | + // Only RSA subject keys should have the KeyEncipherment KeyUsage bits set. In |
| 83 | + // the context of TLS this KeyUsage is particular to RSA key exchange and |
| 84 | + // authentication. |
| 85 | + if _, isRSA := priv.(*rsa.PrivateKey); isRSA { |
| 86 | + keyUsage |= x509.KeyUsageKeyEncipherment |
| 87 | + } |
| 88 | + |
| 89 | + var notBefore time.Time |
| 90 | + if len(*validFrom) == 0 { |
| 91 | + notBefore = time.Now() |
| 92 | + } else { |
| 93 | + notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom) |
| 94 | + if err != nil { |
| 95 | + return fmt.Errorf("Failed to parse creation date: %v", err) |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + notAfter := notBefore.Add(*validFor) |
| 100 | + |
| 101 | + serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) |
| 102 | + serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) |
| 103 | + if err != nil { |
| 104 | + return fmt.Errorf("Failed to generate serial number: %v", err) |
| 105 | + } |
| 106 | + |
| 107 | + template := x509.Certificate{ |
| 108 | + SerialNumber: serialNumber, |
| 109 | + Subject: pkix.Name{ |
| 110 | + Organization: []string{"Red Hat Inc."}, |
| 111 | + }, |
| 112 | + NotBefore: notBefore, |
| 113 | + NotAfter: notAfter, |
| 114 | + |
| 115 | + KeyUsage: keyUsage, |
| 116 | + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 117 | + BasicConstraintsValid: true, |
| 118 | + } |
| 119 | + |
| 120 | + hosts := strings.Split(host, ",") |
| 121 | + for _, h := range hosts { |
| 122 | + if ip := net.ParseIP(h); ip != nil { |
| 123 | + template.IPAddresses = append(template.IPAddresses, ip) |
| 124 | + } else { |
| 125 | + template.DNSNames = append(template.DNSNames, h) |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + if *isCA { |
| 130 | + template.IsCA = true |
| 131 | + template.KeyUsage |= x509.KeyUsageCertSign |
| 132 | + } |
| 133 | + |
| 134 | + derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv) |
| 135 | + if err != nil { |
| 136 | + return fmt.Errorf("Failed to create certificate: %v", err) |
| 137 | + } |
| 138 | + |
| 139 | + certOut, err := os.Create("cert.pem") |
| 140 | + if err != nil { |
| 141 | + return fmt.Errorf("Failed to open cert.pem for writing: %v", err) |
| 142 | + } |
| 143 | + if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { |
| 144 | + return fmt.Errorf("Failed to write data to cert.pem: %v", err) |
| 145 | + } |
| 146 | + if err := certOut.Close(); err != nil { |
| 147 | + return fmt.Errorf("Error closing cert.pem: %v", err) |
| 148 | + } |
| 149 | + // log.Print("wrote cert.pem\n") |
| 150 | + |
| 151 | + keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) |
| 152 | + if err != nil { |
| 153 | + return fmt.Errorf("Failed to open key.pem for writing: %v", err) |
| 154 | + } |
| 155 | + privBytes, err := x509.MarshalPKCS8PrivateKey(priv) |
| 156 | + if err != nil { |
| 157 | + return fmt.Errorf("Unable to marshal private key: %v", err) |
| 158 | + } |
| 159 | + if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { |
| 160 | + return fmt.Errorf("Failed to write data to key.pem: %v", err) |
| 161 | + } |
| 162 | + if err := keyOut.Close(); err != nil { |
| 163 | + return fmt.Errorf("Error closing key.pem: %v", err) |
| 164 | + } |
| 165 | + // log.Print("wrote key.pem\n") |
| 166 | + return nil |
| 167 | +} |
0 commit comments