generateHostCert creates a TLS certificate for the given host, signed by the CA.
(ca *tls.Certificate, host string)
| 56 | |
| 57 | // generateHostCert creates a TLS certificate for the given host, signed by the CA. |
| 58 | func generateHostCert(ca *tls.Certificate, host string) (*tls.Certificate, error) { |
| 59 | key, err := rsa.GenerateKey(rand.Reader, 2048) |
| 60 | if err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | |
| 64 | serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) |
| 65 | if err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | |
| 69 | template := &x509.Certificate{ |
| 70 | SerialNumber: serial, |
| 71 | Subject: pkix.Name{ |
| 72 | CommonName: host, |
| 73 | }, |
| 74 | NotBefore: time.Now().Add(-time.Hour), |
| 75 | NotAfter: time.Now().Add(365 * 24 * time.Hour), |
| 76 | KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, |
| 77 | ExtKeyUsage: []x509.ExtKeyUsage{ |
| 78 | x509.ExtKeyUsageServerAuth, |
| 79 | }, |
| 80 | } |
| 81 | |
| 82 | if ip := net.ParseIP(host); ip != nil { |
| 83 | template.IPAddresses = []net.IP{ip} |
| 84 | } else { |
| 85 | template.DNSNames = []string{host} |
| 86 | } |
| 87 | |
| 88 | certDER, err := x509.CreateCertificate(rand.Reader, template, ca.Leaf, &key.PublicKey, ca.PrivateKey) |
| 89 | if err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | |
| 93 | return &tls.Certificate{ |
| 94 | Certificate: [][]byte{certDER}, |
| 95 | PrivateKey: key, |
| 96 | }, nil |
| 97 | } |