50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package mtls
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"fmt"
|
|
"os"
|
|
|
|
"google.golang.org/grpc/credentials"
|
|
)
|
|
|
|
// LoadMTLSCredentials loads client certificate and CA certificate for mTLS.
|
|
func LoadMTLSCredentials(caCertPEM, clientCertPEM, clientKeyPEM []byte) (credentials.TransportCredentials, error) {
|
|
cert, err := tls.X509KeyPair(clientCertPEM, clientKeyPEM)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("load client key pair: %w", err)
|
|
}
|
|
|
|
caCertPool := x509.NewCertPool()
|
|
if !caCertPool.AppendCertsFromPEM(caCertPEM) {
|
|
return nil, fmt.Errorf("failed to append CA certificate")
|
|
}
|
|
|
|
tlsConfig := &tls.Config{
|
|
Certificates: []tls.Certificate{cert},
|
|
RootCAs: caCertPool,
|
|
MinVersion: tls.VersionTLS12,
|
|
}
|
|
|
|
return credentials.NewTLS(tlsConfig), nil
|
|
}
|
|
|
|
// LoadMTLSCredentialsFromFiles loads mTLS credentials from file paths.
|
|
func LoadMTLSCredentialsFromFiles(caCertPath, clientCertPath, clientKeyPath string) (credentials.TransportCredentials, error) {
|
|
caCert, err := os.ReadFile(caCertPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read CA cert: %w", err)
|
|
}
|
|
clientCert, err := os.ReadFile(clientCertPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read client cert: %w", err)
|
|
}
|
|
clientKey, err := os.ReadFile(clientKeyPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read client key: %w", err)
|
|
}
|
|
|
|
return LoadMTLSCredentials(caCert, clientCert, clientKey)
|
|
}
|