github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/common/fabhttp/tls.go (about) 1 /* 2 Copyright hechain All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package fabhttp 8 9 import ( 10 "crypto/tls" 11 "crypto/x509" 12 "io/ioutil" 13 14 "github.com/hechain20/hechain/internal/pkg/comm" 15 ) 16 17 type TLS struct { 18 Enabled bool 19 CertFile string 20 KeyFile string 21 ClientCertRequired bool 22 ClientCACertFiles []string 23 } 24 25 func (t TLS) Config() (*tls.Config, error) { 26 var tlsConfig *tls.Config 27 28 if t.Enabled { 29 cert, err := tls.LoadX509KeyPair(t.CertFile, t.KeyFile) 30 if err != nil { 31 return nil, err 32 } 33 caCertPool := x509.NewCertPool() 34 for _, caPath := range t.ClientCACertFiles { 35 caPem, err := ioutil.ReadFile(caPath) 36 if err != nil { 37 return nil, err 38 } 39 caCertPool.AppendCertsFromPEM(caPem) 40 } 41 tlsConfig = &tls.Config{ 42 MinVersion: tls.VersionTLS12, 43 Certificates: []tls.Certificate{cert}, 44 CipherSuites: comm.DefaultTLSCipherSuites, 45 ClientCAs: caCertPool, 46 } 47 if t.ClientCertRequired { 48 tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert 49 } else { 50 tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven 51 } 52 } 53 54 return tlsConfig, nil 55 }