forked from cretz/caddy-tlsconsul
-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
crypto.go
95 lines (79 loc) · 2.37 KB
/
crypto.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
package storageconsul
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
)
func (cs *ConsulStorage) encrypt(bytes []byte) ([]byte, error) {
// No key? No encrypt
if len(cs.AESKey) == 0 {
return bytes, nil
}
c, err := aes.NewCipher(cs.AESKey)
if err != nil {
return nil, fmt.Errorf("unable to create AES cipher: %w", err)
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, fmt.Errorf("unable to create GCM cipher: %w", err)
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, fmt.Errorf("unable to generate nonce: %w", err)
}
return gcm.Seal(nonce, nonce, bytes, nil), nil
}
func (cs *ConsulStorage) EncryptStorageData(data *StorageData) ([]byte, error) {
// JSON marshal, then encrypt if key is there
bytes, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("unable to marshal: %w", err)
}
// Prefix with simple prefix and then encrypt
bytes = append([]byte(cs.ValuePrefix), bytes...)
return cs.encrypt(bytes)
}
func (cs *ConsulStorage) decrypt(bytes []byte) ([]byte, error) {
// No key? No decrypt
if len(cs.AESKey) == 0 {
return bytes, nil
}
if len(bytes) < aes.BlockSize {
return nil, errors.New("invalid contents")
}
block, err := aes.NewCipher(cs.AESKey)
if err != nil {
return nil, fmt.Errorf("unable to create AES cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("unable to create GCM cipher: %w", err)
}
out, err := gcm.Open(nil, bytes[:gcm.NonceSize()], bytes[gcm.NonceSize():], nil)
if err != nil {
return nil, fmt.Errorf("decryption failure: %w", err)
}
return out, nil
}
func (cs *ConsulStorage) DecryptStorageData(bytes []byte) (*StorageData, error) {
// We have to decrypt if there is an AES key and then JSON unmarshal
bytes, err := cs.decrypt(bytes)
if err != nil {
return nil, fmt.Errorf("unable to decrypt data: %w", err)
}
// Simple sanity check of the beginning of the byte array just to check
if len(bytes) < len(cs.ValuePrefix) || string(bytes[:len(cs.ValuePrefix)]) != cs.ValuePrefix {
return nil, errors.New("invalid data format")
}
// Now just json unmarshal
data := &StorageData{}
if err := json.Unmarshal(bytes[len(cs.ValuePrefix):], data); err != nil {
return nil, fmt.Errorf("unable to unmarshal result: %w", err)
}
return data, nil
}