-
Notifications
You must be signed in to change notification settings - Fork 351
/
encrypter.go
186 lines (168 loc) · 4.28 KB
/
encrypter.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
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
package secrets
import (
"crypto/aes"
"crypto/cipher"
crand "crypto/rand"
"fmt"
"io"
"io/ioutil"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/scrypt"
)
// SecretSource
type SecretSource interface {
GetSecret() ([][]byte, error)
}
type fileSecretSource struct {
fileName string
}
func (fss *fileSecretSource) GetSecret() ([][]byte, error) {
contents, err := ioutil.ReadFile(fss.fileName)
if err != nil {
return nil, err
}
secrets := strings.Split(string(contents), ",")
byteSecrets := make([][]byte, len(secrets))
for i, s := range secrets {
byteSecrets[i] = []byte(s)
if len(byteSecrets[i]) == 0 {
return nil, fmt.Errorf("file %s secret %d is empty", fss.fileName, i)
}
}
if len(byteSecrets) == 0 {
return nil, fmt.Errorf("secrets file %s is empty", fss.fileName)
}
return byteSecrets, nil
}
func newFileSecretSource(file string) SecretSource {
return &fileSecretSource{fileName: file}
}
type Encrypter struct {
cipherSuites []cipher.AEAD
mux sync.RWMutex
secretSource SecretSource
closer chan struct{}
closedHook chan struct{}
}
func newEncrypter(secretsFile string) (*Encrypter, error) {
secretSource := newFileSecretSource(secretsFile)
_, err := secretSource.GetSecret()
if err != nil {
return nil, fmt.Errorf("failed to read secrets from secret source: %v", err)
}
return &Encrypter{
secretSource: secretSource,
closer: make(chan struct{}),
}, nil
}
// WithSource can be used to create an Encrypter, for example in
// secrettest for testing purposes.
func WithSource(s SecretSource) (*Encrypter, error) {
return &Encrypter{
secretSource: s,
closer: make(chan struct{}),
}, nil
}
func (e *Encrypter) CreateNonce() ([]byte, error) {
e.mux.RLock()
defer e.mux.RUnlock()
if len(e.cipherSuites) > 0 {
nonce := make([]byte, e.cipherSuites[0].NonceSize())
if _, err := io.ReadFull(crand.Reader, nonce); err != nil {
return nil, err
}
return nonce, nil
}
return nil, fmt.Errorf("no ciphers which can be used")
}
// Encrypt encrypts given plaintext
func (e *Encrypter) Encrypt(plaintext []byte) ([]byte, error) {
e.mux.RLock()
defer e.mux.RUnlock()
if len(e.cipherSuites) > 0 {
nonce, err := e.CreateNonce()
if err != nil {
return nil, err
}
return e.cipherSuites[0].Seal(nonce, nonce, plaintext, nil), nil
}
return nil, fmt.Errorf("no ciphers which can be used")
}
// Decrypt decrypts given cipher text
func (e *Encrypter) Decrypt(cipherText []byte) ([]byte, error) {
e.mux.RLock()
defer e.mux.RUnlock()
for _, c := range e.cipherSuites {
nonceSize := c.NonceSize()
if len(cipherText) < nonceSize {
return nil, fmt.Errorf("failed to decrypt, ciphertext too short %d", len(cipherText))
}
nonce, input := cipherText[:nonceSize], cipherText[nonceSize:]
data, err := c.Open(nil, nonce, input, nil)
if err == nil {
return data, nil
}
}
return nil, fmt.Errorf("none of the ciphers can decrypt the data")
}
// RefreshCiphers rotates the list of cipher.AEAD initialized with
// SecretSource from the Encrypter.
func (e *Encrypter) RefreshCiphers() error {
secrets, err := e.secretSource.GetSecret()
if err != nil {
return err
}
suites := make([]cipher.AEAD, len(secrets))
for i, s := range secrets {
key, err := scrypt.Key(s, []byte{}, 1<<15, 8, 1, 32)
if err != nil {
return fmt.Errorf("failed to create key: %v", err)
}
//key has to be 16 or 32 byte
block, err := aes.NewCipher(key)
if err != nil {
return fmt.Errorf("failed to create new cipher: %v", err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return fmt.Errorf("failed to create new GCM: %v", err)
}
suites[i] = aesgcm
}
e.mux.Lock()
defer e.mux.Unlock()
e.cipherSuites = suites
return nil
}
func (e *Encrypter) runCipherRefresher(refreshInterval time.Duration) error {
err := e.RefreshCiphers()
if err != nil {
return err
}
go func() {
ticker := time.NewTicker(refreshInterval)
for {
select {
case <-e.closer:
if e.closedHook != nil {
close(e.closedHook)
}
return
case <-ticker.C:
log.Debug("started refresh of ciphers")
err := e.RefreshCiphers()
if err != nil {
log.Error("failed to refresh the ciphers")
}
log.Debug("finished refresh of ciphers")
}
}
}()
return nil
}
func (e *Encrypter) Close() {
close(e.closer)
}