forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
76 lines (61 loc) · 1.78 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
}