-
Notifications
You must be signed in to change notification settings - Fork 0
/
tink.go
69 lines (56 loc) · 1.28 KB
/
tink.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
package cvault
import (
"context"
"crypto/rand"
"io"
"github.com/google/tink/go/aead"
"github.com/google/tink/go/keyset"
"github.com/vmihailenco/msgpack/v5"
)
const (
keyLength = 32
nonceLength = 24
)
type payload struct {
Nonce []byte
Message []byte
}
func encryptWithTink(ctx context.Context, keyUrl string, data []byte) ([]byte, error) {
dek := aead.AES128CTRHMACSHA256KeyTemplate()
kh, err := keyset.NewHandle(aead.KMSEnvelopeAEADKeyTemplate(keyUrl, dek))
if err != nil {
return nil, err
}
a, err := aead.New(kh)
if err != nil {
return nil, err
}
nonce := make([]byte, nonceLength)
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
encrypted, err := a.Encrypt(data, nonce)
if err != nil {
return nil, err
}
return msgpack.Marshal(&payload{
Message: encrypted,
Nonce: nonce,
})
}
func decryptWithTink(ctx context.Context, keyUrl string, data []byte) ([]byte, error) {
var p payload
if err := msgpack.Unmarshal(data, &p); err != nil {
return nil, err
}
dek := aead.AES128CTRHMACSHA256KeyTemplate()
kh, err := keyset.NewHandle(aead.KMSEnvelopeAEADKeyTemplate(keyUrl, dek))
if err != nil {
return nil, err
}
a, err := aead.New(kh)
if err != nil {
return nil, err
}
return a.Decrypt(p.Message, p.Nonce[:])
}