-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
71 lines (66 loc) · 1.6 KB
/
utils.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
package main
import (
"log"
"os"
"github.com/google/tink/go/aead"
"github.com/google/tink/go/core/registry"
"github.com/google/tink/go/insecurecleartextkeyset"
"github.com/google/tink/go/keyset"
)
func GenerateKeyset() *keyset.Handle {
handle, err := keyset.NewHandle(aead.AES256GCMKeyTemplate())
if err != nil {
log.Fatal(err)
}
return handle
}
func WriteKeySet(path, masterKeyURI string, handle *keyset.Handle) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatal(err.Error())
}
jsonWriter := keyset.NewJSONWriter(f)
if masterKeyURI != "" {
kmsClient, err := registry.GetKMSClient(masterKeyURI)
if err != nil {
log.Fatal(err)
}
registry.RegisterKMSClient(kmsClient)
masterKey, err := kmsClient.GetAEAD(masterKeyURI)
if err != nil {
log.Fatal(err)
}
handle.Write(jsonWriter, masterKey)
} else {
insecurecleartextkeyset.Write(handle, jsonWriter)
}
}
func ReadKeySet(path, masterKeyURI string) *keyset.Handle {
f, err := os.OpenFile(path, os.O_RDONLY, 0600)
if err != nil {
log.Fatal(err.Error())
}
jsonReader := keyset.NewJSONReader(f)
var handle *keyset.Handle
if masterKeyURI != "" {
kmsClient, err := registry.GetKMSClient(masterKeyURI)
if err != nil {
log.Fatal(err)
}
registry.RegisterKMSClient(kmsClient)
masterKey, err := kmsClient.GetAEAD(masterKeyURI)
if err != nil {
log.Fatal(err)
}
handle, err = keyset.Read(jsonReader, masterKey)
if err != nil {
log.Fatal(err.Error())
}
} else {
handle, err = insecurecleartextkeyset.Read(jsonReader)
if err != nil {
log.Fatal(err.Error())
}
}
return handle
}