github.com/OrigamiWang/msd/micro@v0.0.0-20240229032328-b62246268db9/auth/tls/tls.go (about)

     1  package tls
     2  
     3  import (
     4  	"crypto/tls"
     5  	"crypto/x509"
     6  	"os"
     7  
     8  	logutil "github.com/OrigamiWang/msd/micro/util/log"
     9  )
    10  
    11  var (
    12  	TlsClientConfig = &tls.Config{}
    13  	TlsServerConfig = &tls.Config{}
    14  )
    15  
    16  func init() {
    17  	var err error
    18  	TlsClientConfig, err = initTlsClientConfig()
    19  	if err != nil {
    20  		logutil.Error("init cls client config failed, err: %v", err)
    21  		panic(err.Error())
    22  	}
    23  	TlsServerConfig, err = initTlsServerConfig()
    24  	if err != nil {
    25  		logutil.Error("init cls server config failed, err: %v", err)
    26  		panic(err.Error())
    27  	}
    28  }
    29  func initCertAndPool() (*tls.Certificate, *x509.CertPool, error) {
    30  	caCert, err := os.ReadFile("conf/ca.crt")
    31  	if err != nil {
    32  		logutil.Error("read ca.crt error: %v", err)
    33  		return nil, nil, err
    34  	}
    35  	caCertPool := x509.NewCertPool()
    36  	caCertPool.AppendCertsFromPEM(caCert)
    37  	clientCert, err := tls.LoadX509KeyPair("conf/client.crt", "conf/client.key")
    38  	if err != nil {
    39  		logutil.Error("read client.crt or client.key error: %v", err)
    40  		return nil, nil, err
    41  	}
    42  	return &clientCert, caCertPool, nil
    43  }
    44  
    45  func initTlsClientConfig() (*tls.Config, error) {
    46  	cert, pool, err := initCertAndPool()
    47  	if err != nil {
    48  		logutil.Error("init certificate and pool failed err: %v", err)
    49  		return nil, err
    50  	}
    51  	tlsConfig := &tls.Config{
    52  		Certificates: []tls.Certificate{*cert},
    53  		RootCAs:      pool,
    54  	}
    55  	return tlsConfig, nil
    56  }
    57  func initTlsServerConfig() (*tls.Config, error) {
    58  	cert, pool, err := initCertAndPool()
    59  	if err != nil {
    60  		logutil.Error("init certificate and pool failed err: %v", err)
    61  		return nil, err
    62  	}
    63  	tlsConfig := &tls.Config{
    64  		Certificates: []tls.Certificate{*cert},
    65  		RootCAs:      pool,
    66  	}
    67  	return tlsConfig, nil
    68  }