...
1
16
17 package tlsutil
18
19 import (
20 "crypto/tls"
21 "crypto/x509"
22 "os"
23
24 "github.com/pkg/errors"
25 )
26
27
28 func NewClientTLS(certFile, keyFile, caFile string, insecureSkipTLSverify bool) (*tls.Config, error) {
29 config := tls.Config{
30 InsecureSkipVerify: insecureSkipTLSverify,
31 }
32
33 if certFile != "" && keyFile != "" {
34 cert, err := CertFromFilePair(certFile, keyFile)
35 if err != nil {
36 return nil, err
37 }
38 config.Certificates = []tls.Certificate{*cert}
39 }
40
41 if caFile != "" {
42 cp, err := CertPoolFromFile(caFile)
43 if err != nil {
44 return nil, err
45 }
46 config.RootCAs = cp
47 }
48
49 return &config, nil
50 }
51
52
53
54
55
56 func CertPoolFromFile(filename string) (*x509.CertPool, error) {
57 b, err := os.ReadFile(filename)
58 if err != nil {
59 return nil, errors.Errorf("can't read CA file: %v", filename)
60 }
61 cp := x509.NewCertPool()
62 if !cp.AppendCertsFromPEM(b) {
63 return nil, errors.Errorf("failed to append certificates from file: %s", filename)
64 }
65 return cp, nil
66 }
67
68
69
70
71
72 func CertFromFilePair(certFile, keyFile string) (*tls.Certificate, error) {
73 cert, err := tls.LoadX509KeyPair(certFile, keyFile)
74 if err != nil {
75 return nil, errors.Wrapf(err, "can't load key pair from cert %s and key %s", certFile, keyFile)
76 }
77 return &cert, err
78 }
79
View as plain text