-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryption.go
More file actions
298 lines (271 loc) · 7.8 KB
/
encryption.go
File metadata and controls
298 lines (271 loc) · 7.8 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package module
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"maps"
"os"
"strings"
)
// FieldEncryptor provides AES-256-GCM encryption for PII fields in data maps.
// It encrypts specific fields before storage and decrypts them on retrieval,
// ensuring data at rest contains no plaintext PII.
type FieldEncryptor struct {
key []byte
enabled bool
}
// encryptedPrefix marks a value as encrypted so we can detect and skip
// already-encrypted data during double-encrypt scenarios.
const encryptedPrefix = "enc::"
// NewFieldEncryptor creates a FieldEncryptor from a key string.
// If the key is empty, encryption is disabled (passthrough mode).
func NewFieldEncryptor(keyStr string) *FieldEncryptor {
if keyStr == "" {
return &FieldEncryptor{enabled: false}
}
hash := sha256.Sum256([]byte(keyStr))
return &FieldEncryptor{
key: hash[:],
enabled: true,
}
}
// NewFieldEncryptorFromEnv creates a FieldEncryptor using the ENCRYPTION_KEY
// environment variable. Returns a disabled encryptor if the var is not set.
func NewFieldEncryptorFromEnv() *FieldEncryptor {
return NewFieldEncryptor(os.Getenv("ENCRYPTION_KEY"))
}
// Enabled returns whether encryption is active.
func (e *FieldEncryptor) Enabled() bool {
return e.enabled
}
// EncryptValue encrypts a single string value using AES-256-GCM.
// Returns the encrypted value prefixed with "enc::" for identification.
func (e *FieldEncryptor) EncryptValue(plaintext string) (string, error) {
if !e.enabled || plaintext == "" {
return plaintext, nil
}
// Already encrypted — skip
if strings.HasPrefix(plaintext, encryptedPrefix) {
return plaintext, nil
}
block, err := aes.NewCipher(e.key)
if err != nil {
return "", fmt.Errorf("failed to create cipher: %w", err)
}
aead, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("failed to create GCM: %w", err)
}
nonce := make([]byte, aead.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("failed to generate nonce: %w", err)
}
ciphertext := aead.Seal(nonce, nonce, []byte(plaintext), nil)
return encryptedPrefix + base64.StdEncoding.EncodeToString(ciphertext), nil
}
// DecryptValue decrypts a single AES-256-GCM encrypted value.
// Values without the "enc::" prefix are returned as-is (plaintext passthrough).
func (e *FieldEncryptor) DecryptValue(encoded string) (string, error) {
if !e.enabled || encoded == "" {
return encoded, nil
}
// Not encrypted — passthrough
if !strings.HasPrefix(encoded, encryptedPrefix) {
return encoded, nil
}
raw := strings.TrimPrefix(encoded, encryptedPrefix)
ciphertext, err := base64.StdEncoding.DecodeString(raw)
if err != nil {
return "", fmt.Errorf("failed to decode base64: %w", err)
}
block, err := aes.NewCipher(e.key)
if err != nil {
return "", fmt.Errorf("failed to create cipher: %w", err)
}
aead, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("failed to create GCM: %w", err)
}
nonceSize := aead.NonceSize()
if len(ciphertext) < nonceSize {
return "", fmt.Errorf("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", fmt.Errorf("decryption failed: %w", err)
}
return string(plaintext), nil
}
// piiFields defines which top-level data map keys contain PII and should
// be encrypted at rest. Nested "messages" arrays are handled separately.
var piiFields = map[string]bool{
"name": true,
"Name": true,
"email": true,
"phone": true,
"phoneNumber": true,
"From": true,
"from": true,
"to": true,
"address": true,
"body": true,
"Body": true,
"message": true,
"reason": true,
}
// EncryptPIIFields encrypts known PII fields in a data map.
// It handles nested "messages" arrays where each message may contain PII.
func (e *FieldEncryptor) EncryptPIIFields(data map[string]any) (map[string]any, error) {
if !e.enabled || data == nil {
return data, nil
}
result := make(map[string]any, len(data))
maps.Copy(result, data)
// Encrypt top-level PII fields
for field := range piiFields {
val, ok := result[field]
if !ok {
continue
}
str, ok := val.(string)
if !ok || str == "" {
continue
}
encrypted, err := e.EncryptValue(str)
if err != nil {
return nil, fmt.Errorf("encrypt field %q: %w", field, err)
}
result[field] = encrypted
}
// Encrypt PII within messages array
if msgs, ok := result["messages"].([]any); ok {
encMsgs := make([]any, len(msgs))
for i, m := range msgs {
msg, ok := m.(map[string]any)
if !ok {
encMsgs[i] = m
continue
}
encMsg := make(map[string]any, len(msg))
maps.Copy(encMsg, msg)
for field := range piiFields {
val, ok := encMsg[field]
if !ok {
continue
}
str, ok := val.(string)
if !ok || str == "" {
continue
}
encrypted, err := e.EncryptValue(str)
if err != nil {
return nil, fmt.Errorf("encrypt message[%d].%s: %w", i, field, err)
}
encMsg[field] = encrypted
}
encMsgs[i] = encMsg
}
result["messages"] = encMsgs
}
return result, nil
}
// DecryptPIIFields decrypts known PII fields in a data map.
// Values without the "enc::" prefix are returned as-is (backward compatible).
func (e *FieldEncryptor) DecryptPIIFields(data map[string]any) (map[string]any, error) {
if !e.enabled || data == nil {
return data, nil
}
result := make(map[string]any, len(data))
maps.Copy(result, data)
// Decrypt top-level PII fields
for field := range piiFields {
val, ok := result[field]
if !ok {
continue
}
str, ok := val.(string)
if !ok || str == "" {
continue
}
decrypted, err := e.DecryptValue(str)
if err != nil {
return nil, fmt.Errorf("decrypt field %q: %w", field, err)
}
result[field] = decrypted
}
// Decrypt PII within messages array
if msgs, ok := result["messages"].([]any); ok {
decMsgs := make([]any, len(msgs))
for i, m := range msgs {
msg, ok := m.(map[string]any)
if !ok {
decMsgs[i] = m
continue
}
decMsg := make(map[string]any, len(msg))
maps.Copy(decMsg, msg)
for field := range piiFields {
val, ok := decMsg[field]
if !ok {
continue
}
str, ok := val.(string)
if !ok || str == "" {
continue
}
decrypted, err := e.DecryptValue(str)
if err != nil {
return nil, fmt.Errorf("decrypt message[%d].%s: %w", i, field, err)
}
decMsg[field] = decrypted
}
decMsgs[i] = decMsg
}
result["messages"] = decMsgs
}
return result, nil
}
// EncryptJSON encrypts an entire JSON payload (for Kafka messages).
// The entire message is encrypted as a single blob.
func (e *FieldEncryptor) EncryptJSON(data []byte) ([]byte, error) {
if !e.enabled || len(data) == 0 {
return data, nil
}
encrypted, err := e.EncryptValue(string(data))
if err != nil {
return nil, err
}
// Wrap in a JSON envelope so consumers know it's encrypted
envelope := map[string]string{
"_encrypted": encrypted,
}
return json.Marshal(envelope)
}
// DecryptJSON decrypts an entire JSON payload (for Kafka messages).
// Non-encrypted payloads (no "_encrypted" key) are returned as-is.
func (e *FieldEncryptor) DecryptJSON(data []byte) ([]byte, error) {
if !e.enabled || len(data) == 0 {
return data, nil
}
// Check if this is an encrypted envelope
var envelope map[string]string
if err := json.Unmarshal(data, &envelope); err != nil {
return data, nil //nolint:nilerr // Not an encrypted envelope, return original data
}
encrypted, ok := envelope["_encrypted"]
if !ok {
// Not an encrypted envelope — return as-is
return data, nil
}
decrypted, err := e.DecryptValue(encrypted)
if err != nil {
return nil, fmt.Errorf("decrypt kafka message: %w", err)
}
return []byte(decrypted), nil
}