-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcert.go
54 lines (49 loc) · 1.16 KB
/
cert.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
package utils
import (
"crypto/tls"
"crypto/x509"
"os"
"google.golang.org/grpc/credentials"
)
// 证书实例
type Cert struct {
Server credentials.TransportCredentials
Client credentials.TransportCredentials
}
// 服务证书
func (c *Cert) NewServer(cafile, pemfiile, keyfile string) (err error) {
var cert tls.Certificate
if cert, err = tls.LoadX509KeyPair(pemfiile, keyfile); err != nil {
return
}
certPool := x509.NewCertPool()
var ca []byte
if ca, err = os.ReadFile(cafile); err != nil {
return
}
certPool.AppendCertsFromPEM(ca)
c.Server = credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: certPool,
})
return
}
// 客户证书
func (c *Cert) NewClient(cafile, pemfiile, keyfile string) (err error) {
var cert tls.Certificate
if cert, err = tls.LoadX509KeyPair(pemfiile, keyfile); err != nil {
return
}
certPool := x509.NewCertPool()
var ca []byte
if ca, err = os.ReadFile(cafile); err != nil {
return
}
certPool.AppendCertsFromPEM(ca)
c.Client = credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: certPool,
})
return
}