Skip to content

Commit

Permalink
serverName 为key,缓存 creds
Browse files Browse the repository at this point in the history
  • Loading branch information
springrain committed Nov 15, 2021
1 parent da89cbe commit a1550e8
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions kernel/network/p2p/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
defaultx509 "crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"io/ioutil"
math_rand "math/rand"
"os"
Expand All @@ -25,7 +26,20 @@ import (
"github.com/xuperchain/xupercore/kernel/network/config"
)

// serverName 为key,缓存 creds
var serverNameMap = make(map[string]credentials.TransportCredentials)

func NewTLS(path, serviceName string) (credentials.TransportCredentials, error) {

if len(serviceName) < 1 {
return nil, errors.New("serviceName is empty")
}

//如果缓存中有值
if creds, ok := serverNameMap[serviceName]; ok {
return creds, nil
}

bs, err := ioutil.ReadFile(filepath.Join(path, "cacert.pem"))
if err != nil {
return nil, err
Expand All @@ -39,7 +53,8 @@ func NewTLS(path, serviceName string) (credentials.TransportCredentials, error)
if err != nil {
return nil, err
}
if strings.Contains(strings.ToLower(x509cert.SignatureAlgorithm.String()), "sm") {

if strings.Contains(strings.ToLower(x509cert.SignatureAlgorithm.String()), "sm") { //国密
certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM(bs)
if !ok {
Expand All @@ -51,16 +66,16 @@ func NewTLS(path, serviceName string) (credentials.TransportCredentials, error)
}
creds := gmcredentials.NewTLS(
&tls.Config{
GMSupport: &tls.GMSupport{},
GMSupport: tls.NewGMSupport(),
ServerName: serviceName,
Certificates: []tls.Certificate{certificate, certificate},
RootCAs: certPool,
ClientCAs: certPool,
ClientAuth: tls.RequireAndVerifyClientCert,
})
serverNameMap[serviceName] = creds
return creds, nil
} else {

} else { //非国密
certPool := defaultx509.NewCertPool()
ok := certPool.AppendCertsFromPEM(bs)
if !ok {
Expand All @@ -80,6 +95,7 @@ func NewTLS(path, serviceName string) (credentials.TransportCredentials, error)
ClientCAs: certPool,
ClientAuth: defaulttls.RequireAndVerifyClientCert,
})
serverNameMap[serviceName] = creds
return creds, nil
}

Expand Down

0 comments on commit a1550e8

Please sign in to comment.