-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt.go
55 lines (46 loc) · 1.29 KB
/
encrypt.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
package transit
import (
"context"
"encoding/base64"
"errors"
"fmt"
)
func (t Transit) Encrypt(ctx context.Context, key, engineName string, req BatchRequestItem) (EncryptBatchResponseItem, error) {
p, err := t.GetKey(ctx, key, engineName)
if err != nil {
return EncryptBatchResponseItem{}, err
}
if p == nil {
return EncryptBatchResponseItem{}, fmt.Errorf("missing policy for key %s", key)
}
if _, err := base64.StdEncoding.DecodeString(req.Plaintext); err != nil {
return EncryptBatchResponseItem{}, err
}
if len(req.Context) != 0 {
req.DecodedContext, err = base64.StdEncoding.DecodeString(req.Context)
if err != nil {
return EncryptBatchResponseItem{}, err
}
}
if len(req.Nonce) != 0 {
var err error
req.DecodedNonce, err = base64.StdEncoding.DecodeString(req.Nonce)
if err != nil {
return EncryptBatchResponseItem{}, err
}
}
ciphertext, err := p.Encrypt(req.KeyVersion, req.DecodedContext, req.DecodedNonce, req.Plaintext)
if err != nil {
return EncryptBatchResponseItem{}, err
}
if ciphertext == "" {
return EncryptBatchResponseItem{}, errors.New("empty ciphertext returned for input item")
}
if req.KeyVersion == 0 {
req.KeyVersion = p.LatestVersion
}
return EncryptBatchResponseItem{
Ciphertext: ciphertext,
KeyVersion: req.KeyVersion,
}, nil
}