Skip to content

Commit 2431df9

Browse files
committed
examples: tls: Add a simple TLS example
Was useful for testing things...
1 parent ed84c54 commit 2431df9

File tree

1 file changed

+203
-0
lines changed

1 file changed

+203
-0
lines changed

examples/tls/tls.go

Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
// Modified from: golang/src/crypto/tls/generate_cert.go
2+
3+
package main
4+
5+
import (
6+
"crypto/ecdsa"
7+
"crypto/ed25519"
8+
"crypto/elliptic"
9+
"crypto/rand"
10+
"crypto/rsa"
11+
"crypto/x509"
12+
"crypto/x509/pkix"
13+
"encoding/pem"
14+
"fmt"
15+
"log"
16+
"math/big"
17+
"net"
18+
"net/http"
19+
"os"
20+
"strings"
21+
"time"
22+
)
23+
24+
// NewTLS builds a new TLS struct with some defaults.
25+
func NewTLS() *TLS {
26+
return &TLS{
27+
ValidFor: 365 * 24 * time.Hour,
28+
RsaBits: 2048,
29+
}
30+
}
31+
32+
// TLS handles all of the TLS building.
33+
type TLS struct {
34+
Host string // Comma-separated hostnames and IPs to generate a certificate for
35+
ValidFrom string // Creation date formatted as Jan 1 15:04:05 2011
36+
ValidFor time.Duration // Duration that certificate is valid for
37+
IsCA bool // Whether this cert should be its own Certificate Authority
38+
RsaBits int // Size of RSA key to generate. Ignored if EcdsaCurve is set
39+
EcdsaCurve string // ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P521
40+
Ed25519Key bool // Generate an Ed25519 key
41+
}
42+
43+
// Generate writes out the two files. Usually keyPemFile is key.pem and
44+
// certPemFile is cert.pem which go into http.ListenAndServeTLS.
45+
func (obj *TLS) Generate(keyPemFile, certPemFile string) error {
46+
47+
if len(obj.Host) == 0 {
48+
return fmt.Errorf("Missing required Host parameter")
49+
}
50+
51+
var priv any
52+
var err error
53+
switch obj.EcdsaCurve {
54+
case "":
55+
if obj.Ed25519Key {
56+
_, priv, err = ed25519.GenerateKey(rand.Reader)
57+
} else {
58+
priv, err = rsa.GenerateKey(rand.Reader, obj.RsaBits)
59+
}
60+
case "P224":
61+
priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
62+
case "P256":
63+
priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
64+
case "P384":
65+
priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
66+
case "P521":
67+
priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
68+
default:
69+
return fmt.Errorf("Unrecognized elliptic curve: %q", obj.EcdsaCurve)
70+
}
71+
if err != nil {
72+
return fmt.Errorf("Failed to generate private key: %v", err)
73+
}
74+
75+
// ECDSA, ED25519 and RSA subject keys should have the DigitalSignature
76+
// KeyUsage bits set in the x509.Certificate template
77+
keyUsage := x509.KeyUsageDigitalSignature
78+
// Only RSA subject keys should have the KeyEncipherment KeyUsage bits set. In
79+
// the context of TLS this KeyUsage is particular to RSA key exchange and
80+
// authentication.
81+
if _, isRSA := priv.(*rsa.PrivateKey); isRSA {
82+
keyUsage |= x509.KeyUsageKeyEncipherment
83+
}
84+
85+
var notBefore time.Time
86+
if len(obj.ValidFrom) == 0 {
87+
notBefore = time.Now()
88+
} else {
89+
notBefore, err = time.Parse("Jan 2 15:04:05 2006", obj.ValidFrom)
90+
if err != nil {
91+
return fmt.Errorf("Failed to parse creation date: %v", err)
92+
}
93+
}
94+
95+
notAfter := notBefore.Add(obj.ValidFor)
96+
97+
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
98+
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
99+
if err != nil {
100+
return fmt.Errorf("Failed to generate serial number: %v", err)
101+
}
102+
103+
template := x509.Certificate{
104+
SerialNumber: serialNumber,
105+
Subject: pkix.Name{
106+
Organization: []string{"Acme Co"}, // XXX: change me...
107+
},
108+
NotBefore: notBefore,
109+
NotAfter: notAfter,
110+
111+
KeyUsage: keyUsage,
112+
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
113+
BasicConstraintsValid: true,
114+
}
115+
116+
hosts := strings.Split(obj.Host, ",")
117+
for _, h := range hosts {
118+
if ip := net.ParseIP(h); ip != nil {
119+
template.IPAddresses = append(template.IPAddresses, ip)
120+
} else {
121+
template.DNSNames = append(template.DNSNames, h)
122+
}
123+
}
124+
125+
if obj.IsCA {
126+
template.IsCA = true
127+
template.KeyUsage |= x509.KeyUsageCertSign
128+
}
129+
130+
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
131+
if err != nil {
132+
return fmt.Errorf("Failed to create certificate: %v", err)
133+
}
134+
135+
certOut, err := os.Create(certPemFile)
136+
if err != nil {
137+
return fmt.Errorf("Failed to open %s for writing: %v", certPemFile, err)
138+
}
139+
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
140+
return fmt.Errorf("Failed to write data to %s: %v", certPemFile, err)
141+
}
142+
if err := certOut.Close(); err != nil {
143+
return fmt.Errorf("Error closing %s: %v", certPemFile, err)
144+
}
145+
log.Printf("wrote %s", certPemFile)
146+
147+
keyOut, err := os.OpenFile(keyPemFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
148+
if err != nil {
149+
return fmt.Errorf("Failed to open %s for writing: %v", keyPemFile, err)
150+
}
151+
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
152+
if err != nil {
153+
return fmt.Errorf("Unable to marshal private key: %v", err)
154+
}
155+
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
156+
return fmt.Errorf("Failed to write data to %s: %v", keyPemFile, err)
157+
}
158+
if err := keyOut.Close(); err != nil {
159+
return fmt.Errorf("Error closing %s: %v", keyPemFile, err)
160+
}
161+
log.Printf("wrote %s", keyPemFile)
162+
163+
return nil
164+
}
165+
166+
// HelloServer is a simple handler.
167+
func HelloServer(w http.ResponseWriter, req *http.Request) {
168+
fmt.Printf("req: %+v\n", req)
169+
w.Header().Set("Content-Type", "text/plain")
170+
w.Write([]byte("This is hello world!\n"))
171+
}
172+
173+
func publicKey(priv any) any {
174+
switch k := priv.(type) {
175+
case *rsa.PrivateKey:
176+
return &k.PublicKey
177+
case *ecdsa.PrivateKey:
178+
return &k.PublicKey
179+
case ed25519.PrivateKey:
180+
return k.Public().(ed25519.PublicKey)
181+
default:
182+
return nil
183+
}
184+
}
185+
186+
func main() {
187+
// wget --no-check-certificate https://127.0.0.1:1443/hello -O -
188+
189+
tls := NewTLS()
190+
tls.Host = "localhost" // TODO: choose something
191+
keyPemFile := "/tmp/key.pem"
192+
certPemFile := "/tmp/cert.pem"
193+
194+
if err := tls.Generate(keyPemFile, certPemFile); err != nil {
195+
fmt.Printf("error: %v\n", err)
196+
return
197+
}
198+
199+
http.HandleFunc("/hello", HelloServer)
200+
if err := http.ListenAndServeTLS(":1443", certPemFile, keyPemFile, nil); err != nil {
201+
log.Fatal("ListenAndServe: ", err)
202+
}
203+
}

0 commit comments

Comments
 (0)