-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls.go
55 lines (50 loc) · 1.02 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
package goutube
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
)
type TLSConfig struct {
CertFile string
KeyFile string
CAFile string
ServerAddress string
Server bool
}
func SetupTLSConfig(cfg TLSConfig) (*tls.Config, error) {
var err error
tlsConfig := &tls.Config{}
if cfg.CertFile != "" && cfg.KeyFile != "" {
tlsConfig.Certificates = make([]tls.Certificate, 1)
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(
cfg.CertFile,
cfg.KeyFile,
)
if err != nil {
return nil, err
}
}
if cfg.CAFile != "" {
b, err := ioutil.ReadFile(cfg.CAFile)
if err != nil {
return nil, err
}
ca := x509.NewCertPool()
ok := ca.AppendCertsFromPEM([]byte(b))
if !ok {
return nil, fmt.Errorf(
"failed to parse root certificate: %q",
cfg.CAFile,
)
}
if cfg.Server {
tlsConfig.ClientCAs = ca
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
} else {
tlsConfig.RootCAs = ca
}
tlsConfig.ServerName = cfg.ServerAddress
}
return tlsConfig, nil
}