6
6
defaultx509 "crypto/x509"
7
7
"encoding/base64"
8
8
"encoding/pem"
9
+ "errors"
9
10
"io/ioutil"
10
11
math_rand "math/rand"
11
12
"os"
@@ -25,7 +26,20 @@ import (
25
26
"github.com/xuperchain/xupercore/kernel/network/config"
26
27
)
27
28
29
+ // serverName 为key,缓存 creds
30
+ var serverNameMap = make (map [string ]credentials.TransportCredentials )
31
+
28
32
func NewTLS (path , serviceName string ) (credentials.TransportCredentials , error ) {
33
+
34
+ if len (serviceName ) < 1 {
35
+ return nil , errors .New ("serviceName is empty" )
36
+ }
37
+
38
+ //如果缓存中有值
39
+ if creds , ok := serverNameMap [serviceName ]; ok {
40
+ return creds , nil
41
+ }
42
+
29
43
bs , err := ioutil .ReadFile (filepath .Join (path , "cacert.pem" ))
30
44
if err != nil {
31
45
return nil , err
@@ -39,7 +53,8 @@ func NewTLS(path, serviceName string) (credentials.TransportCredentials, error)
39
53
if err != nil {
40
54
return nil , err
41
55
}
42
- if strings .Contains (strings .ToLower (x509cert .SignatureAlgorithm .String ()), "sm" ) {
56
+
57
+ if strings .Contains (strings .ToLower (x509cert .SignatureAlgorithm .String ()), "sm" ) { //国密
43
58
certPool := x509 .NewCertPool ()
44
59
ok := certPool .AppendCertsFromPEM (bs )
45
60
if ! ok {
@@ -51,16 +66,16 @@ func NewTLS(path, serviceName string) (credentials.TransportCredentials, error)
51
66
}
52
67
creds := gmcredentials .NewTLS (
53
68
& tls.Config {
54
- GMSupport : & tls.GMSupport {} ,
69
+ GMSupport : tls .NewGMSupport () ,
55
70
ServerName : serviceName ,
56
71
Certificates : []tls.Certificate {certificate , certificate },
57
72
RootCAs : certPool ,
58
73
ClientCAs : certPool ,
59
74
ClientAuth : tls .RequireAndVerifyClientCert ,
60
75
})
76
+ serverNameMap [serviceName ] = creds
61
77
return creds , nil
62
- } else {
63
-
78
+ } else { //非国密
64
79
certPool := defaultx509 .NewCertPool ()
65
80
ok := certPool .AppendCertsFromPEM (bs )
66
81
if ! ok {
@@ -80,6 +95,7 @@ func NewTLS(path, serviceName string) (credentials.TransportCredentials, error)
80
95
ClientCAs : certPool ,
81
96
ClientAuth : defaulttls .RequireAndVerifyClientCert ,
82
97
})
98
+ serverNameMap [serviceName ] = creds
83
99
return creds , nil
84
100
}
85
101
0 commit comments