-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls.go
56 lines (52 loc) · 1.41 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
package main
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"log"
)
func createTLSConfig(pemFile, pemCertFile, pemPrivateKeyFile string, insecureSkipVerify bool) *tls.Config {
if insecureSkipVerify {
// pem settings are irrelevent if we're skipping verification anyway
return &tls.Config{
InsecureSkipVerify: true,
}
}
if len(pemFile) <= 0 {
return nil
}
rootCerts, err := loadCertificatesFrom(pemFile)
if err != nil {
log.Fatalf("Couldn't load root certificate from %s. Got %s.", pemFile, err)
}
if len(pemCertFile) > 0 && len(pemPrivateKeyFile) > 0 {
clientPrivateKey, err := loadPrivateKeyFrom(pemCertFile, pemPrivateKeyFile)
if err != nil {
log.Fatalf("Couldn't setup client authentication. Got %s.", err)
}
return &tls.Config{
RootCAs: rootCerts,
Certificates: []tls.Certificate{*clientPrivateKey},
}
}
return &tls.Config{
RootCAs: rootCerts,
InsecureSkipVerify: insecureSkipVerify,
}
}
func loadCertificatesFrom(pemFile string) (*x509.CertPool, error) {
caCert, err := ioutil.ReadFile(pemFile)
if err != nil {
return nil, err
}
certificates := x509.NewCertPool()
certificates.AppendCertsFromPEM(caCert)
return certificates, nil
}
func loadPrivateKeyFrom(pemCertFile, pemPrivateKeyFile string) (*tls.Certificate, error) {
privateKey, err := tls.LoadX509KeyPair(pemCertFile, pemPrivateKeyFile)
if err != nil {
return nil, err
}
return &privateKey, nil
}