github.com/y-taka-23/helm@v2.8.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  	config := tls.Config{
    33  		Certificates: []tls.Certificate{*cert},
    34  	}
    35  	if caFile != "" {
    36  		cp, err := CertPoolFromFile(caFile)
    37  		if err != nil {
    38  			return nil, err
    39  		}
    40  		config.RootCAs = cp
    41  	}
    42  	return &config, nil
    43  }
    44  
    45  // CertPoolFromFile returns an x509.CertPool containing the certificates
    46  // in the given PEM-encoded file.
    47  // Returns an error if the file could not be read, a certificate could not
    48  // be parsed, or if the file does not contain any certificates
    49  func CertPoolFromFile(filename string) (*x509.CertPool, error) {
    50  	b, err := ioutil.ReadFile(filename)
    51  	if err != nil {
    52  		return nil, fmt.Errorf("can't read CA file: %v", filename)
    53  	}
    54  	cp := x509.NewCertPool()
    55  	if !cp.AppendCertsFromPEM(b) {
    56  		return nil, fmt.Errorf("failed to append certificates from file: %s", filename)
    57  	}
    58  	return cp, nil
    59  }
    60  
    61  // CertFromFilePair returns an tls.Certificate containing the
    62  // certificates public/private key pair from a pair of given PEM-encoded files.
    63  // Returns an error if the file could not be read, a certificate could not
    64  // be parsed, or if the file does not contain any certificates
    65  func CertFromFilePair(certFile, keyFile string) (*tls.Certificate, error) {
    66  	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
    67  	if err != nil {
    68  		return nil, fmt.Errorf("can't load key pair from cert %s and key %s: %s", certFile, keyFile, err)
    69  	}
    70  	return &cert, err
    71  }