-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathkms.go
60 lines (53 loc) · 1.3 KB
/
kms.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
// Copyright (c) 2022 EPAM Systems, Inc.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package gcp
import (
"context"
"crypto/rand"
"time"
kms "cloud.google.com/go/kms/apiv1"
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)
const aes256KeySize = 32
var (
kmsTimeout = time.Duration(10 * time.Second)
)
func KmsKey(name string, blob []byte) ([]byte, []byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), kmsTimeout)
defer cancel()
kms, err := kms.NewKeyManagementClient(ctx)
if err != nil {
return nil, nil, err
}
defer kms.Close()
// new data key for encryption
if len(blob) == 0 {
key := make([]byte, aes256KeySize)
_, err := rand.Read(key)
if err != nil {
return nil, nil, err
}
req := &kmspb.EncryptRequest{
Name: name,
Plaintext: key,
}
result, err := kms.Encrypt(ctx, req)
if err != nil {
return nil, nil, err
}
return key, result.Ciphertext, nil
}
// decrypt data key for decryption
req := &kmspb.DecryptRequest{
Name: name,
Ciphertext: blob,
}
result, err := kms.Decrypt(ctx, req)
if err != nil {
return nil, nil, err
}
return result.Plaintext, blob, nil
}