forked from hashicorp/terraform-provider-tls
/
data_source_public_key.go
70 lines (63 loc) · 1.83 KB
/
data_source_public_key.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
package tls
import (
"encoding/pem"
"fmt"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourcePublicKey() *schema.Resource {
return &schema.Resource{
Read: dataSourcePublicKeyRead,
Schema: map[string]*schema.Schema{
"private_key_pem": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "PEM formatted string to use as the private key",
},
"algorithm": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Name of the algorithm to use to generate the private key",
},
"public_key_pem": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"public_key_openssh": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"public_key_fingerprint_md5": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourcePublicKeyRead(d *schema.ResourceData, meta interface{}) error {
// Read private key
bytes := []byte("")
if v, ok := d.GetOk("private_key_pem"); ok {
bytes = []byte(v.(string))
} else {
return fmt.Errorf("invalid private key %#v", v)
}
// decode PEM encoding to ANS.1 PKCS1 DER
keyPemBlock, _ := pem.Decode(bytes)
if keyPemBlock == nil || (keyPemBlock.Type != "RSA PRIVATE KEY" && keyPemBlock.Type != "EC PRIVATE KEY") {
return fmt.Errorf("failed to decode PEM block containing private key of type %#v", keyPemBlock.Type)
}
keyAlgo := ""
switch keyPemBlock.Type {
case "RSA PRIVATE KEY":
keyAlgo = "RSA"
case "EC PRIVATE KEY":
keyAlgo = "ECDSA"
}
d.Set("algorithm", keyAlgo)
// Converts a private key from its ASN.1 PKCS#1 DER encoded form
key, err := parsePrivateKey(d, "private_key_pem", "algorithm")
if err != nil {
return fmt.Errorf("error converting key to algo: %s - %s", keyAlgo, err)
}
return readPublicKey(d, key)
}