-
Notifications
You must be signed in to change notification settings - Fork 13
/
datasource_pfx.go
111 lines (94 loc) · 2.51 KB
/
datasource_pfx.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package ddcloud
import (
"bytes"
"encoding/pem"
"io/ioutil"
"log"
"github.com/hashicorp/terraform/helper/schema"
"golang.org/x/crypto/pkcs12"
)
const (
resourceKeyPFXFile = "file"
resourceKeyPFXPassword = "password"
resourceKeyPFXCertificate = "certificate"
resourceKeyPFXPrivateKey = "private_key"
)
func dataSourcePFX() *schema.Resource {
return &schema.Resource{
Read: dataSourcePFXRead,
Schema: map[string]*schema.Schema{
resourceKeyPFXFile: &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The name of the PFX file",
},
resourceKeyPFXPassword: &schema.Schema{
Type: schema.TypeString,
Required: true,
Sensitive: true,
Description: "The password for the PFX file",
},
resourceKeyPFXCertificate: &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "The (first) certificate in the PFX file",
},
resourceKeyPFXPrivateKey: &schema.Schema{
Type: schema.TypeString,
Computed: true,
Sensitive: true,
Description: "The (first) private key in the PFX file",
},
},
}
}
// Read a network domain data source.
func dataSourcePFXRead(data *schema.ResourceData, provider interface{}) error {
fileName := data.Get(resourceKeyPFXFile).(string)
pfxData, err := ioutil.ReadFile(fileName)
if err != nil {
log.Printf("Failed to read PFX data from '%s': %s", fileName, err.Error())
return err
}
log.Printf("Read PFX data from '%s'.", fileName)
pfxPassword := data.Get(resourceKeyPFXPassword).(string)
pemBlocks, err := pkcs12.ToPEM(pfxData, pfxPassword)
if err != nil {
log.Printf("Failed to decode PFX data from '%s': %s", fileName, err.Error())
return err
}
var (
certificatePEM string
privateKeyPEM string
)
for _, pemBlock := range pemBlocks {
switch pemBlock.Type {
case "CERTIFICATE":
if certificatePEM == "" {
certificatePEM, err = pemToString(pemBlock)
if err != nil {
return err
}
}
case "PRIVATE KEY":
if privateKeyPEM == "" {
privateKeyPEM, err = pemToString(pemBlock)
if err != nil {
return err
}
}
}
}
data.Set(resourceKeyPFXCertificate, certificatePEM)
data.Set(resourceKeyPFXPrivateKey, privateKeyPEM)
return nil
}
func pemToString(pemBlock *pem.Block) (string, error) {
var buffer bytes.Buffer
err := pem.Encode(&buffer, pemBlock)
if err != nil {
log.Printf("Failed to decode '%s' PEM block: %s", pemBlock.Type, err.Error())
return "", err
}
return buffer.String(), nil
}