-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Certification.go
76 lines (63 loc) · 1.47 KB
/
Certification.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
package auth
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"google.golang.org/grpc/credentials"
)
type Certificate struct {
CAFile string
CertFile string
KeyFile string
ServerName string
}
func (c Certificate) GetTLSConfigForServer() (*tls.Config, error) {
certificate, err := tls.LoadX509KeyPair(
c.CertFile,
c.KeyFile,
)
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
bs, err := ioutil.ReadFile(c.CAFile)
if err != nil {
return nil, fmt.Errorf("failed to read client ca cert: %s", err)
}
ok := certPool.AppendCertsFromPEM(bs)
if !ok {
return nil, errors.New("failed to append client certs")
}
tlsConfig := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{certificate},
ClientCAs: certPool,
}
return tlsConfig, nil
}
func (c Certificate) GetTransportCredsForClient() (credentials.TransportCredentials, error) {
certificate, err := tls.LoadX509KeyPair(
c.CertFile,
c.KeyFile,
)
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
bs, err := ioutil.ReadFile(c.CAFile)
if err != nil {
return nil, fmt.Errorf("failed to read ca cert: %s", err)
}
ok := certPool.AppendCertsFromPEM(bs)
if !ok {
return nil, errors.New("failed to append certs")
}
transportCreds := credentials.NewTLS(&tls.Config{
ServerName: c.ServerName,
Certificates: []tls.Certificate{certificate},
RootCAs: certPool,
})
return transportCreds, nil
}