2017-05-23 18:56:10 +00:00
|
|
|
package crypto
|
2016-08-01 01:40:12 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509"
|
|
|
|
"io/ioutil"
|
|
|
|
)
|
|
|
|
|
2018-05-19 14:25:11 +00:00
|
|
|
// CreateTLSConfigurationFromBytes initializes a tls.Config using a CA certificate, a certificate and a key
|
|
|
|
// loaded from memory.
|
|
|
|
func CreateTLSConfigurationFromBytes(caCert, cert, key []byte, skipClientVerification, skipServerVerification bool) (*tls.Config, error) {
|
2018-04-16 11:19:24 +00:00
|
|
|
config := &tls.Config{}
|
|
|
|
config.InsecureSkipVerify = skipServerVerification
|
|
|
|
|
|
|
|
if !skipClientVerification {
|
|
|
|
certificate, err := tls.X509KeyPair(cert, key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
config.Certificates = []tls.Certificate{certificate}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !skipServerVerification {
|
|
|
|
caCertPool := x509.NewCertPool()
|
|
|
|
caCertPool.AppendCertsFromPEM(caCert)
|
|
|
|
config.RootCAs = caCertPool
|
|
|
|
}
|
|
|
|
|
|
|
|
return config, nil
|
|
|
|
}
|
|
|
|
|
2018-05-19 14:25:11 +00:00
|
|
|
// CreateTLSConfigurationFromDisk initializes a tls.Config using a CA certificate, a certificate and a key
|
|
|
|
// loaded from disk.
|
|
|
|
func CreateTLSConfigurationFromDisk(caCertPath, certPath, keyPath string, skipServerVerification bool) (*tls.Config, error) {
|
|
|
|
config := &tls.Config{}
|
|
|
|
config.InsecureSkipVerify = skipServerVerification
|
2017-08-10 08:35:23 +00:00
|
|
|
|
2018-05-19 14:25:11 +00:00
|
|
|
if certPath != "" && keyPath != "" {
|
|
|
|
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
|
2017-09-21 15:19:43 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2017-08-10 08:35:23 +00:00
|
|
|
}
|
|
|
|
|
2018-05-19 14:25:11 +00:00
|
|
|
config.Certificates = []tls.Certificate{cert}
|
2017-09-21 15:19:43 +00:00
|
|
|
}
|
2017-09-14 06:08:37 +00:00
|
|
|
|
2018-05-19 14:25:11 +00:00
|
|
|
if !skipServerVerification && caCertPath != "" {
|
|
|
|
caCert, err := ioutil.ReadFile(caCertPath)
|
2017-09-21 15:19:43 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2017-08-10 08:35:23 +00:00
|
|
|
}
|
2017-09-14 06:08:37 +00:00
|
|
|
|
2017-09-21 15:19:43 +00:00
|
|
|
caCertPool := x509.NewCertPool()
|
|
|
|
caCertPool.AppendCertsFromPEM(caCert)
|
2018-05-19 14:25:11 +00:00
|
|
|
config.RootCAs = caCertPool
|
2016-08-01 01:40:12 +00:00
|
|
|
}
|
2017-08-10 08:35:23 +00:00
|
|
|
|
2018-05-19 14:25:11 +00:00
|
|
|
return config, nil
|
2016-08-01 01:40:12 +00:00
|
|
|
}
|