-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls.go
70 lines (61 loc) · 1.88 KB
/
tls.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package x
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"time"
"gitlab.com/tozd/go/errors"
)
// CreateTempCertificateFiles creates a pair of files for given domains.
// It generates a ECDSA private key.
func CreateTempCertificateFiles(certPath, keyPath string, domains []string) errors.E {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return errors.WithStack(err)
}
// Create a self-signed certificate.
template := x509.Certificate{ //nolint:exhaustruct
SerialNumber: big.NewInt(1),
Subject: pkix.Name{Organization: []string{"Test"}}, //nolint:exhaustruct
NotBefore: time.Now().UTC(),
NotAfter: time.Now().UTC().Add(24 * time.Hour), //nolint:mnd
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
DNSNames: domains,
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return errors.WithStack(err)
}
// Write the certificate to a file.
certFile, err := os.Create(certPath)
if err != nil {
return errors.WithStack(err)
}
defer certFile.Close()
err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certDER}) //nolint:exhaustruct
if err != nil {
return errors.WithStack(err)
}
// Write the private key to a file.
keyFile, err := os.Create(keyPath)
if err != nil {
return errors.WithStack(err)
}
defer keyFile.Close()
privBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return errors.WithStack(err)
}
err = pem.Encode(keyFile, &pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes}) //nolint:exhaustruct
if err != nil {
return errors.WithStack(err)
}
return nil
}