-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtls_utils.go
More file actions
71 lines (60 loc) · 1.8 KB
/
tls_utils.go
File metadata and controls
71 lines (60 loc) · 1.8 KB
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
71
package aviation
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"github.com/pkg/errors"
)
// GetClientTLSConfig creates a creates a client-side TLS configuration based
// on the given cas, cert, and key. If possible, the system cert pool is
// combined with the provided cas.
func GetClientTLSConfig(cas [][]byte, crt, key []byte) (*tls.Config, error) {
cp, err := GetCACertPool(cas...)
if err != nil {
return nil, err
}
keyPair, err := tls.X509KeyPair(crt, key)
if err != nil {
return nil, errors.Wrap(err, "reading the client cert")
}
return &tls.Config{
Certificates: []tls.Certificate{keyPair},
RootCAs: cp,
}, nil
}
// GetCACertPool is a convenience function that creates a cert pool with the
// given cas and, when possible, the system cert pool. On windows machines, the
// cert pool will be empty if no cas are passed in.
func GetCACertPool(cas ...[]byte) (*x509.CertPool, error) {
cp, err := x509.SystemCertPool()
if err != nil {
return nil, errors.Wrap(err, "getting system cert pool")
}
for _, ca := range cas {
if !cp.AppendCertsFromPEM(ca) {
return nil, errors.New("appending CA certificate to the cert pool")
}
}
return cp, nil
}
// GetClientTLSConfigFromFiles creates a creates a client-side TLS
// configuration based on the given ca, cert, and key files.
func GetClientTLSConfigFromFiles(caFiles []string, crtFile, keyFile string) (*tls.Config, error) {
cas := make([][]byte, len(caFiles))
for i, caFile := range caFiles {
ca, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, errors.WithStack(err)
}
cas[i] = ca
}
crt, err := ioutil.ReadFile(crtFile)
if err != nil {
return nil, errors.WithStack(err)
}
key, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, errors.WithStack(err)
}
return GetClientTLSConfig(cas, crt, key)
}