-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
93 lines (78 loc) · 2.29 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
package tlsclouddatastore
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/json"
"fmt"
"io"
)
const valuePrefix = "caddy-tlsconsul"
func (cds *CloudDsStorage) encrypt(bytes []byte) ([]byte, error) {
// No key? No encrypt
if len(cds.aesKey) == 0 {
return bytes, nil
}
c, err := aes.NewCipher(cds.aesKey)
if err != nil {
return nil, fmt.Errorf("Unable to create AES cipher: %v", err)
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, fmt.Errorf("Unable to create GCM cipher: %v", err)
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, fmt.Errorf("Unable to generate nonce: %v", err)
}
return gcm.Seal(nonce, nonce, bytes, nil), nil
}
func (cds *CloudDsStorage) toBytes(iface interface{}) ([]byte, error) {
// JSON marshal, then encrypt if key is there
bytes, err := json.Marshal(iface)
if err != nil {
return nil, fmt.Errorf("Unable to marshal: %v", err)
}
// Prefix with simple prefix and then encrypt
bytes = append([]byte(valuePrefix), bytes...)
return cds.encrypt(bytes)
}
func (cds *CloudDsStorage) decrypt(bytes []byte) ([]byte, error) {
// No key? No decrypt
if len(cds.aesKey) == 0 {
return bytes, nil
}
if len(bytes) < aes.BlockSize {
return nil, fmt.Errorf("Invalid contents")
}
block, err := aes.NewCipher(cds.aesKey)
if err != nil {
return nil, fmt.Errorf("Unable to create AES cipher: %v", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("Unable to create GCM cipher: %v", err)
}
out, err := gcm.Open(nil, bytes[:gcm.NonceSize()], bytes[gcm.NonceSize():], nil)
if err != nil {
return nil, fmt.Errorf("Decryption failure: %v", err)
}
return out, nil
}
func (cds *CloudDsStorage) fromBytes(bytes []byte, iface interface{}) error {
// We have to decrypt if there is an AES key and then JSON unmarshal
bytes, err := cds.decrypt(bytes)
if err != nil {
return err
}
// Simple sanity check of the beginning of the byte array just to check
if len(bytes) < len(valuePrefix) || string(bytes[:len(valuePrefix)]) != valuePrefix {
return fmt.Errorf("Invalid data format")
}
// Now just json unmarshal
if err := json.Unmarshal(bytes[len(valuePrefix):], iface); err != nil {
return fmt.Errorf("Unable to unmarshal result: %v", err)
}
return nil
}