-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathciphercrypter.go
96 lines (81 loc) · 2.25 KB
/
ciphercrypter.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package dyno
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
"golang.org/x/crypto/chacha20poly1305"
)
// NewAESCrypter creates a new KeyCrypter that encrypts DynamoDB primary key attributes
// with AES GCM encryption.
// The key must be 16, 24, or 32 bytes long to select AES-128, AES-192, or AES-256.
func NewAESCrypter(key []byte) (KeyCrypter, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
mode, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &cipherCrypterItem{
mode: mode,
}, nil
}
// NewChaCha20Poly1305Crypter creates a new KeyCrypter that encrypts DynamoDB
// primary key attributes with ChaCha20-Poly1305 encryption.
// The key must be 32 bytes long.
func NewChaCha20Poly1305Crypter(key []byte) (KeyCrypter, error) {
block, err := chacha20poly1305.New(key)
if err != nil {
return nil, err
}
return &cipherCrypterItem{
mode: block,
}, nil
}
type cipherCrypterItem struct {
mode cipher.AEAD
}
// Encrypt encrypts a dynamodb item along with an encryption context.
// A random nonce is used for each encryption operation.
// The nonce is prepended to the cipher text.
func (c *cipherCrypterItem) Encrypt(ctx context.Context,
item map[string]types.AttributeValue,
) (string, error) {
plainText, err := serialize(item)
if err != nil {
return "", err
}
nonce := make([]byte, c.mode.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
cipherText := c.mode.Seal(nil, nonce, plainText, nil)
cipherText = append(nonce, cipherText...)
return base64.URLEncoding.EncodeToString(cipherText), nil
}
// Decrypt decrypts a dynamodb item along with an encryption context.
// The item must have been encrypted with the same encryption context.
func (c *cipherCrypterItem) Decrypt(
ctx context.Context,
itemStr string,
) (map[string]types.AttributeValue, error) {
nonceAndCipherText, err := base64.URLEncoding.DecodeString(itemStr)
if err != nil {
return nil, err
}
plainText, err := c.mode.Open(
nil,
nonceAndCipherText[:c.mode.NonceSize()],
nonceAndCipherText[c.mode.NonceSize():],
nil,
)
if err != nil {
return nil, err
}
return deserialize(plainText)
}