github.com/zoumo/helm@v2.5.0+incompatible/pkg/tlsutil/tls.go (about)

     1  /*
     2  Copyright 2016 The Kubernetes Authors All rights reserved.
     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  	"fmt"
    23  	"io/ioutil"
    24  )
    25  
    26  // NewClientTLS returns tls.Config appropriate for client auth.
    27  func NewClientTLS(certFile, keyFile, caFile string) (*tls.Config, error) {
    28  	cert, err := CertFromFilePair(certFile, keyFile)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  	cp, err := CertPoolFromFile(caFile)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	return &tls.Config{
    37  		Certificates: []tls.Certificate{*cert},
    38  		RootCAs:      cp,
    39  	}, nil
    40  }
    41  
    42  // CertPoolFromFile returns an x509.CertPool containing the certificates
    43  // in the given PEM-encoded file.
    44  // Returns an error if the file could not be read, a certificate could not
    45  // be parsed, or if the file does not contain any certificates
    46  func CertPoolFromFile(filename string) (*x509.CertPool, error) {
    47  	b, err := ioutil.ReadFile(filename)
    48  	if err != nil {
    49  		return nil, fmt.Errorf("can't read CA file: %v", filename)
    50  	}
    51  	cp := x509.NewCertPool()
    52  	if !cp.AppendCertsFromPEM(b) {
    53  		return nil, fmt.Errorf("failed to append certificates from file: %s", filename)
    54  	}
    55  	return cp, nil
    56  }
    57  
    58  // CertFromFilePair returns an tls.Certificate containing the
    59  // certificates public/private key pair from a pair of given PEM-encoded files.
    60  // Returns an error if the file could not be read, a certificate could not
    61  // be parsed, or if the file does not contain any certificates
    62  func CertFromFilePair(certFile, keyFile string) (*tls.Certificate, error) {
    63  	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
    64  	if err != nil {
    65  		return nil, fmt.Errorf("can't load key pair from cert %s and key %s", certFile, keyFile)
    66  	}
    67  	return &cert, err
    68  }