certifer/grpc.go

56 lines
1.3 KiB
Go
Raw Permalink Normal View History

2022-11-04 19:38:34 +01:00
package certifer
import (
"crypto/tls"
"crypto/x509"
"errors"
"google.golang.org/grpc/credentials"
)
func (c *Cert) GrpcServerConfig() (credentials.TransportCredentials, error) {
if c.CA == nil {
return nil, errors.New("security blob contains no CA")
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(c.CA.CertAsPem()) {
return nil, errors.New("cannot add CA to pool")
}
tCertPem := c.CertAsPem()
tKeyPem, _ := c.KeyAsPem()
tCert, err := tls.X509KeyPair(tCertPem, tKeyPem)
if err != nil {
return nil, err
}
config := &tls.Config{
Certificates: []tls.Certificate{tCert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: certPool,
}
creds := credentials.NewTLS(config)
return creds, nil
}
func (c *Cert) GrpcClientConfig() (credentials.TransportCredentials, error) {
if c.CA == nil {
return nil, errors.New("security blob contains no CA")
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(c.CA.CertAsPem()) {
return nil, errors.New("cannot add CA to pool")
}
tCertPem := c.CertAsPem()
tKeyPem, _ := c.KeyAsPem()
tCert, err := tls.X509KeyPair(tCertPem, tKeyPem)
if err != nil {
return nil, err
}
config := &tls.Config{
Certificates: []tls.Certificate{tCert},
RootCAs: certPool,
}
creds := credentials.NewTLS(config)
return creds, nil
}