github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/tls/util.go (about)

     1  package tls
     2  
     3  import (
     4  	"crypto/x509"
     5  	"encoding/pem"
     6  	"fmt"
     7  
     8  	"github.com/hashicorp/terraform/helper/schema"
     9  )
    10  
    11  func decodePEM(d *schema.ResourceData, pemKey, pemType string) (*pem.Block, error) {
    12  	block, _ := pem.Decode([]byte(d.Get(pemKey).(string)))
    13  	if block == nil {
    14  		return nil, fmt.Errorf("no PEM block found in %s", pemKey)
    15  	}
    16  	if pemType != "" && block.Type != pemType {
    17  		return nil, fmt.Errorf("invalid PEM type in %s: %s", pemKey, block.Type)
    18  	}
    19  
    20  	return block, nil
    21  }
    22  
    23  func parsePrivateKey(d *schema.ResourceData, pemKey, algoKey string) (interface{}, error) {
    24  	algoName := d.Get(algoKey).(string)
    25  
    26  	keyFunc, ok := keyParsers[algoName]
    27  	if !ok {
    28  		return nil, fmt.Errorf("invalid %s: %#v", algoKey, algoName)
    29  	}
    30  
    31  	block, err := decodePEM(d, pemKey, "")
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	key, err := keyFunc(block.Bytes)
    37  	if err != nil {
    38  		return nil, fmt.Errorf("failed to decode %s: %s", pemKey, err)
    39  	}
    40  
    41  	return key, nil
    42  }
    43  
    44  func parseCertificate(d *schema.ResourceData, pemKey string) (*x509.Certificate, error) {
    45  	block, err := decodePEM(d, pemKey, "")
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	certs, err := x509.ParseCertificates(block.Bytes)
    51  	if err != nil {
    52  		return nil, fmt.Errorf("failed to parse %s: %s", pemKey, err)
    53  	}
    54  	if len(certs) < 1 {
    55  		return nil, fmt.Errorf("no certificates found in %s", pemKey)
    56  	}
    57  	if len(certs) > 1 {
    58  		return nil, fmt.Errorf("multiple certificates found in %s", pemKey)
    59  	}
    60  
    61  	return certs[0], nil
    62  }
    63  
    64  func parseCertificateRequest(d *schema.ResourceData, pemKey string) (*x509.CertificateRequest, error) {
    65  	block, err := decodePEM(d, pemKey, pemCertReqType)
    66  	if err != nil {
    67  		return nil, err
    68  	}
    69  
    70  	certReq, err := x509.ParseCertificateRequest(block.Bytes)
    71  	if err != nil {
    72  		return nil, fmt.Errorf("failed to parse %s: %s", pemKey, err)
    73  	}
    74  
    75  	return certReq, nil
    76  }