-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathwrapped.go
73 lines (63 loc) · 1.9 KB
/
wrapped.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
package secrets
import (
"context"
"fmt"
"google.golang.org/api/option"
kms "cloud.google.com/go/kms/apiv1"
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)
// APIWrapper wraps the GCP api
type APIWrapper struct {
ProjectID string
LocationID string
KmsRing string
KmsKey string
KmsClient *kms.KeyManagementClient
}
func NewClinet(ctx context.Context, opts Option, credentials string) (*Client, error) {
kmsClient, err := kms.NewKeyManagementClient(ctx, option.WithCredentialsFile(credentials))
if err != nil {
return nil, fmt.Errorf("kms client create error %w", err)
}
api := &APIWrapper{
ProjectID: opts.ProjectID,
LocationID: opts.LocationID,
KmsRing: opts.KmsRing,
KmsKey: opts.KmsKey,
KmsClient: kmsClient,
}
if client, err := New(opts, api); err != nil {
return nil, fmt.Errorf("secrets client create error %w", err)
} else {
return client, nil
}
}
// Encrypt calls the wrapped GCP api to encrypt a secret
func (caw *APIWrapper) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) {
req := &kmspb.EncryptRequest{
Name: caw.getKmsKeyPath(),
Plaintext: plaintext,
}
resp, err := caw.KmsClient.Encrypt(ctx, req)
if err != nil {
return nil, fmt.Errorf("Encrypting secret failed: %w", err)
}
return resp.Ciphertext, nil
}
// Decrypt calls the wrapped GCP api to decrypt a secret
func (caw *APIWrapper) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) {
// Build the request.
req := &kmspb.DecryptRequest{
Name: caw.getKmsKeyPath(),
Ciphertext: ciphertext,
}
// Call the API.
resp, err := caw.KmsClient.Decrypt(ctx, req)
if err != nil {
return nil, fmt.Errorf("Decrypting secret failed: %w", err)
}
return resp.Plaintext, nil
}
func (caw *APIWrapper) getKmsKeyPath() string {
return fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s", caw.ProjectID, caw.LocationID, caw.KmsRing, caw.KmsKey)
}