package tls import ( "crypto/x509" "encoding/pem" "fmt" "github.com/hashicorp/terraform/helper/schema" ) func decodePEM(d *schema.ResourceData, pemKey, pemType string) (*pem.Block, error) { block, _ := pem.Decode([]byte(d.Get(pemKey).(string))) if block == nil { return nil, fmt.Errorf("no PEM block found in %s", pemKey) } if pemType != "" && block.Type != pemType { return nil, fmt.Errorf("invalid PEM type in %s: %s", pemKey, block.Type) } return block, nil } func parsePrivateKey(d *schema.ResourceData, pemKey, algoKey string) (interface{}, error) { algoName := d.Get(algoKey).(string) keyFunc, ok := keyParsers[algoName] if !ok { return nil, fmt.Errorf("invalid %s: %#v", algoKey, algoName) } block, err := decodePEM(d, pemKey, "") if err != nil { return nil, err } key, err := keyFunc(block.Bytes) if err != nil { return nil, fmt.Errorf("failed to decode %s: %s", pemKey, err) } return key, nil } func parseCertificate(d *schema.ResourceData, pemKey string) (*x509.Certificate, error) { block, err := decodePEM(d, pemKey, "") if err != nil { return nil, err } certs, err := x509.ParseCertificates(block.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse %s: %s", pemKey, err) } if len(certs) < 1 { return nil, fmt.Errorf("no certificates found in %s", pemKey) } if len(certs) > 1 { return nil, fmt.Errorf("multiple certificates found in %s", pemKey) } return certs[0], nil } func parseCertificateRequest(d *schema.ResourceData, pemKey string) (*x509.CertificateRequest, error) { block, err := decodePEM(d, pemKey, pemCertReqType) if err != nil { return nil, err } certReq, err := x509.ParseCertificateRequest(block.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse %s: %s", pemKey, err) } return certReq, nil }