forked from zhufuyi/sponge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
51 lines (42 loc) · 1.73 KB
/
server.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
// Package gtls provides grpc secure connectivity, supporting both server-only authentication and client-server authentication.
package gtls
import (
"crypto/tls"
"crypto/x509"
"errors"
"os"
"google.golang.org/grpc/credentials"
)
// GetServerTLSCredentialsByCA two-way authentication via CA-issued root certificate
func GetServerTLSCredentialsByCA(caFile string, certFile string, keyFile string) (credentials.TransportCredentials, error) {
//read and parse the information from the certificate file to obtain the certificate public key, key pair
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
// create an empty CertPool
certPool := x509.NewCertPool()
ca, err := os.ReadFile(caFile)
if err != nil {
return nil, err
}
//attempts to parse the incoming PEM-encoded certificate. If the parsing is successful it will be added to the CertPool for later use
if ok := certPool.AppendCertsFromPEM(ca); !ok {
return nil, errors.New("certPool.AppendCertsFromPEM err")
}
//building TLS-based TransportCredentials options
c := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert}, // set up a certificate chain that allows the inclusion of one or more
ClientAuth: tls.RequireAndVerifyClientCert, // requirement to verify the client's certificate
ClientCAs: certPool, // set the set of root certificates and use the mode set in ClientAuth for verification
})
return c, err
}
// GetServerTLSCredentials server-side authentication
func GetServerTLSCredentials(certFile string, keyFile string) (credentials.TransportCredentials, error) {
c, err := credentials.NewServerTLSFromFile(certFile, keyFile)
if err != nil {
return nil, err
}
return c, err
}