github.com/qsis/helm@v3.0.0-beta.3+incompatible/internal/tlsutil/tls.go (about)

     1  /*
     2  Copyright The Helm Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package tlsutil
    18  
    19  import (
    20  	"crypto/tls"
    21  	"crypto/x509"
    22  	"io/ioutil"
    23  
    24  	"github.com/pkg/errors"
    25  )
    26  
    27  // NewClientTLS returns tls.Config appropriate for client auth.
    28  func NewClientTLS(certFile, keyFile, caFile string) (*tls.Config, error) {
    29  	cert, err := CertFromFilePair(certFile, keyFile)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	config := tls.Config{
    34  		Certificates: []tls.Certificate{*cert},
    35  	}
    36  	if caFile != "" {
    37  		cp, err := CertPoolFromFile(caFile)
    38  		if err != nil {
    39  			return nil, err
    40  		}
    41  		config.RootCAs = cp
    42  	}
    43  	return &config, nil
    44  }
    45  
    46  // CertPoolFromFile returns an x509.CertPool containing the certificates
    47  // in the given PEM-encoded file.
    48  // Returns an error if the file could not be read, a certificate could not
    49  // be parsed, or if the file does not contain any certificates
    50  func CertPoolFromFile(filename string) (*x509.CertPool, error) {
    51  	b, err := ioutil.ReadFile(filename)
    52  	if err != nil {
    53  		return nil, errors.Errorf("can't read CA file: %v", filename)
    54  	}
    55  	cp := x509.NewCertPool()
    56  	if !cp.AppendCertsFromPEM(b) {
    57  		return nil, errors.Errorf("failed to append certificates from file: %s", filename)
    58  	}
    59  	return cp, nil
    60  }
    61  
    62  // CertFromFilePair returns an tls.Certificate containing the
    63  // certificates public/private key pair from a pair of given PEM-encoded files.
    64  // Returns an error if the file could not be read, a certificate could not
    65  // be parsed, or if the file does not contain any certificates
    66  func CertFromFilePair(certFile, keyFile string) (*tls.Certificate, error) {
    67  	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
    68  	if err != nil {
    69  		return nil, errors.Wrapf(err, "can't load key pair from cert %s and key %s", certFile, keyFile)
    70  	}
    71  	return &cert, err
    72  }