This repository has been archived by the owner on Jan 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 302
/
tls.go
82 lines (68 loc) · 1.44 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
71
72
73
74
75
76
77
78
79
80
81
82
package pkg
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"io/ioutil"
)
type keypairFunc func(certPEMBlock, keyPEMBlock []byte) (cert tls.Certificate, err error)
func buildTLSClientConfig(ca, cert, key []byte, parseKeyPair keypairFunc) (*tls.Config, error) {
if len(cert) == 0 && len(key) == 0 {
return &tls.Config{InsecureSkipVerify: true}, nil
}
tlsCert, err := parseKeyPair(cert, key)
if err != nil {
return nil, err
}
cfg := tls.Config{
Certificates: []tls.Certificate{tlsCert},
MinVersion: tls.VersionTLS10,
}
if len(ca) != 0 {
cp, err := newCertPool(ca)
if err != nil {
return nil, err
}
cfg.RootCAs = cp
}
return &cfg, nil
}
func newCertPool(ca []byte) (*x509.CertPool, error) {
certPool := x509.NewCertPool()
for {
var block *pem.Block
block, ca = pem.Decode(ca)
if block == nil {
break
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
certPool.AddCert(cert)
}
return certPool, nil
}
func ReadTLSConfigFiles(cafile, certfile, keyfile string) (cfg *tls.Config, err error) {
var ca, cert, key []byte
if certfile != "" {
cert, err = ioutil.ReadFile(certfile)
if err != nil {
return
}
}
if keyfile != "" {
key, err = ioutil.ReadFile(keyfile)
if err != nil {
return
}
}
if cafile != "" {
ca, err = ioutil.ReadFile(cafile)
if err != nil {
return
}
}
cfg, err = buildTLSClientConfig(ca, cert, key, tls.X509KeyPair)
return
}