-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathkeys.go
256 lines (206 loc) · 5.84 KB
/
keys.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
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
package main
// manage AES keys via KeyCzar / dkeyczar
import (
"fmt"
"io/ioutil"
"os"
"strconv"
dkeyczar "github.com/dgryski/dkeyczar"
)
type CypherKey struct {
Mgr *dkeyczar.KeyManager
Loc string
crypter dkeyczar.Crypter
VerboseDebug bool
HashOfKey32Bytes [32]byte
}
// convenience method for getting started
func OpenExistingOrCreateNewKey(cfg *Config) (key *CypherKey, err error) {
if KeyExists(cfg) {
return LoadKey(cfg)
}
return NewKey(cfg)
}
func KeyExists(cfg *Config) bool {
loc := cfg.KeyLocation()
if !DirExists(loc) {
return false
}
if !FileExists(loc + "/meta") {
return false
}
if !FileExists(loc + "/1") {
return false
}
return true
}
func NewKey(cfg *Config) (key *CypherKey, err error) {
key = &CypherKey{VerboseDebug: cfg.DebugMode}
km := *MakeKeyMgr()
key.Loc = cfg.KeyLocation()
if !DirExists(key.Loc) {
os.MkdirAll(key.Loc, 0700)
} else {
// we already have a key directory, so just make a new key and promote it
return nil, fmt.Errorf("location '%s' already has a key it", key.Loc)
}
updateKeyDir(key.Loc, km, nil)
// make actual key
c := loadCrypter("")
err = loadLocationReader(km, key.Loc, c)
if err != nil {
panic(fmt.Sprintf("could not load keyset from location '%s': %s", key.Loc, err))
}
status := dkeyczar.S_PRIMARY
//status := dkeyczar.S_ACTIVE
//status := dkeyczar.S_INACTIVE
err = km.AddKey(uint(0), status)
if err != nil {
panic(fmt.Sprintf("error adding key: %s", err))
}
updateKeyDir(key.Loc, km, c)
// don't need these if we create with S_PRIMARY, but
// here's how to promote to primary if needed later.
if status != dkeyczar.S_PRIMARY {
keyversion := 1
km.Promote(keyversion)
updateKeyDir(key.Loc, km, nil)
}
key.Mgr = &km
key.InstantiateCrypter()
return key, nil
}
func (k *CypherKey) SetHash(km dkeyczar.KeyManager, c dkeyczar.Crypter) {
}
func (k *CypherKey) DeleteKey() (err error) {
if DirExists(k.Loc) {
return os.RemoveAll(k.Loc)
}
return nil
}
func MakeKeyMgr() *dkeyczar.KeyManager {
// make key set
keytype := dkeyczar.T_AES
km := dkeyczar.NewKeyManager()
keypurpose := dkeyczar.P_DECRYPT_AND_ENCRYPT
km.Create("goq.aes.key", keypurpose, keytype)
return &km
}
func LoadKey(cfg *Config) (*CypherKey, error) {
loc := cfg.KeyLocation()
if !DirExists(loc) {
return nil, fmt.Errorf("request to LoadKey from bad Loc: %s", loc)
}
km := *MakeKeyMgr()
err := loadLocationReader(km, loc, nil)
if err != nil {
return nil, fmt.Errorf("could not load keyset from location '%s': %s", loc, err)
}
k := &CypherKey{Mgr: &km, Loc: loc, VerboseDebug: cfg.DebugMode}
k.InstantiateCrypter()
return k, nil
}
func (k *CypherKey) InstantiateCrypter() {
c := loadCrypter("")
r := loadReader(k.Loc, c)
if r == nil {
panic(fmt.Sprintf("could not read keys from '%s'", k.Loc))
}
// a crypter can decode as well as encode
crypter, err := dkeyczar.NewCrypter(r)
if err != nil {
panic(err)
}
crypter.SetEncoding(dkeyczar.NO_ENCODING)
//crypter.SetEncoding(dkeyczar.BASE64W)
k.crypter = crypter
// NB: assumes there is only ever the one key. If key rotation gets implemented
// in the future, the km.ToJSONs(c)[1] in the next line will need to change the 1
// to reflect the actual key in use.
jsonSlice := (*(k.Mgr)).ToJSONs(c)[1]
k.HashOfKey32Bytes = HashAlotSha256([]byte(jsonSlice))
}
func (k *CypherKey) Encrypt(plain []byte) []byte {
output, err := k.crypter.Encrypt(plain)
if err != nil {
panic(err)
}
//fmt.Printf("Encrypt() is using nacl key '%s'\n", k.HashOfKey32Bytes)
return NaClEncryptWithRandomNoncePrepended([]byte(output), &(k.HashOfKey32Bytes))
}
func (k *CypherKey) Decrypt(cypher []byte) []byte {
//fmt.Printf("Decrypt() is using nacl key '%s'\n", k.HashOfKey32Bytes)
unboxed, ok := NaclDecryptWithNoncePrepended(cypher, &(k.HashOfKey32Bytes))
if !ok {
if k.VerboseDebug {
fmt.Fprintf(os.Stderr, "\n Alert: two-clusters trying to communicate? could not do first-stage decryption.\n")
}
return []byte{}
}
output, err := k.crypter.Decrypt(string(unboxed))
if err != nil {
if k.VerboseDebug {
fmt.Fprintf(os.Stderr, "\n Alert: two-clusters trying to communicate? could not decrypt message: %s\n", err)
}
return []byte{}
//panic(err)
}
return output
}
func (k *CypherKey) IsValid() bool {
plain := []byte("hello world")
cypher := k.Encrypt(plain)
cs := string(cypher)
plain2 := string(k.Decrypt(cypher))
//fmt.Printf("plain: '%s', cypher: '%s', plain2: '%s'\n", plain, cypher, plain2)
if cs != string(plain) && string(plain) == plain2 {
return true
}
return false
}
func updateKeyDir(location string, km dkeyczar.KeyManager, encrypter dkeyczar.Encrypter) {
s := km.ToJSONs(encrypter)
ioutil.WriteFile(location+"/meta", []byte(s[0]), 0600)
for i := 1; i < len(s); i++ {
fname := location + "/" + strconv.Itoa(i)
ioutil.WriteFile(fname, []byte(s[i]), 0600)
}
}
func loadLocationReader(km dkeyczar.KeyManager, location string, crypter dkeyczar.Crypter) error {
if location == "" {
panic("missing required location argument")
}
lr := dkeyczar.NewFileReader(location)
if crypter != nil {
//fmt.Println("decrypting keys..")
lr = dkeyczar.NewEncryptedReader(lr, crypter)
}
err := km.Load(lr)
if err != nil {
return fmt.Errorf("failed to load key: %s", err)
}
return nil
}
func loadCrypter(optCrypter string) dkeyczar.Crypter {
if optCrypter == "" {
return nil
}
//fmt.Println("using crypter:", optCrypter)
r := dkeyczar.NewFileReader(optCrypter)
crypter, err := dkeyczar.NewCrypter(r)
if err != nil {
panic(fmt.Sprintf("failed to load crypter: %s", err))
}
return crypter
}
func loadReader(optLocation string, crypter dkeyczar.Crypter) dkeyczar.KeyReader {
if optLocation == "" {
panic("missing required location argument")
}
lr := dkeyczar.NewFileReader(optLocation)
if crypter != nil {
//fmt.Println("decrypting keys..")
lr = dkeyczar.NewEncryptedReader(lr, crypter)
}
return lr
}