-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcp.go
94 lines (79 loc) · 2.02 KB
/
gcp.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
package nvault
import (
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"net/http"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
kms "google.golang.org/api/cloudkms/v1"
)
// GcpCryptor ...
type GcpCryptor struct {
GcpConfig
}
// GcpConfig ...
type GcpConfig struct {
GcpKmsResourceID string
GcpCredentialFile string
}
// Encrypt ...
func (c *GcpCryptor) Encrypt(value interface{}) (interface{}, error) {
if c.GcpKmsResourceID == "" {
return nil, errors.New("missing Gcp KMS Resource ID")
}
strvalue := fmt.Sprintf("%v", value)
svc, err := serviceGcp(&c.GcpConfig)
if err != nil {
return nil, err
}
response, err := svc.Projects.Locations.KeyRings.CryptoKeys.Encrypt(c.GcpKmsResourceID, &kms.EncryptRequest{
Plaintext: strvalue,
}).Do()
if err != nil {
return nil, err
}
encoded := base64.StdEncoding.EncodeToString([]byte(response.Ciphertext))
return encoded, nil
}
// Decrypt ...
func (c *GcpCryptor) Decrypt(value interface{}) (interface{}, error) {
strvalue := fmt.Sprintf("%v", value)
decoded, err := base64.StdEncoding.DecodeString(strvalue)
if err != nil {
return nil, err
}
svc, err := serviceGcp(&c.GcpConfig)
response, err := svc.Projects.Locations.KeyRings.CryptoKeys.Decrypt(c.GcpKmsResourceID, &kms.DecryptRequest{
Ciphertext: string(decoded),
}).Do()
if err != nil {
return value, nil
}
return string(response.Plaintext), nil
}
func serviceGcp(c *GcpConfig) (*kms.Service, error) {
client, err := createGcpClient(c)
if err != nil {
return nil, err
}
return kms.New(client)
}
func createGcpClient(c *GcpConfig) (client *http.Client, err error) {
ctx := context.Background()
if c.GcpCredentialFile != "" {
data, err := ioutil.ReadFile(c.GcpCredentialFile)
if err != nil {
return nil, err
}
creds, err := google.CredentialsFromJSON(ctx, data, kms.CloudPlatformScope)
if err != nil {
return nil, err
}
client = oauth2.NewClient(ctx, creds.TokenSource)
return client, nil
}
return google.DefaultClient(ctx, kms.CloudPlatformScope)
}