-
Notifications
You must be signed in to change notification settings - Fork 1
/
aes.go
86 lines (70 loc) · 1.69 KB
/
aes.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
package pii
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
)
type SecretProvider[K any] interface {
SecretForKey(ctx context.Context, key K) ([]byte, error)
}
type AESAnonymizer[K any] struct {
secretProvider SecretProvider[K]
}
func NewAESAnonymizer[K any](secretProvider SecretProvider[K]) AESAnonymizer[K] {
return AESAnonymizer[K]{
secretProvider: secretProvider,
}
}
func (a AESAnonymizer[K]) AnonymizeString(ctx context.Context, key K, value string) (string, error) {
secret, err := a.secretProvider.SecretForKey(ctx, key)
if err != nil {
return "", err
}
block, err := aes.NewCipher(secret)
if err != nil {
return "", err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, aead.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := aead.Seal(nonce, nonce, []byte(value), nil)
return fmt.Sprintf("%x", ciphertext), nil
}
func (a AESAnonymizer[K]) DeanonymizeString(ctx context.Context, key K, value string) (string, error) {
secret, err := a.secretProvider.SecretForKey(ctx, key)
if err != nil {
return "", err
}
block, err := aes.NewCipher(secret)
if err != nil {
return "", err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
decoded, err := hex.DecodeString(value)
if err != nil {
return "", err
}
nonceSize := aead.NonceSize()
if len(decoded) < nonceSize {
return "", errors.New("ciphertext too short")
}
nonce, cipherText := decoded[:nonceSize], decoded[nonceSize:]
data, err := aead.Open(nil, nonce, cipherText, nil)
if err != nil {
return "", err
}
return string(data), nil
}