-
Notifications
You must be signed in to change notification settings - Fork 16
/
key_store.go
290 lines (234 loc) · 6.71 KB
/
key_store.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package keys
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
)
type AccountKey struct {
Version int `json:"version"`
CipherText string `json:"cipher_text"`
Address string `json:"address"`
}
const (
EmptyStr = ""
VERSION = 1
)
type keystore interface {
//Hash passphrase so we can get a key that is the correct length for the block cipher.
createHash(key string) string
//encrypt data using the given passphrase.
encrypt(data []byte, passphrase string) ([]byte, error)
//decrypt data using the given passphrase.
decrypt(data []byte, passphrase string) ([]byte, error)
//Encrypt data and store in the given path.
SaveKeyData(path string, address Address, data []byte, passphrase string) error
//Open encrypted file and decrypt data using the key generated from the passphrase.
GetKeyData(path string, address Address, passphrase string) ([]byte, error)
//Delete data associated with given address
DeleteKey(path string, address Address, passphrase string) error
//Verify client has correct password for the given address.
VerifyPassphrase(path string, address Address, passphrase string) (bool, error)
//Check if key exists
KeyExists(path string, address Address) bool
//Get address of account given a file name.
GetAddress(path string, filename string) (Address, error)
}
type KeyStore struct {
}
var _ keystore = &KeyStore{}
func (ks *KeyStore) createHash(key string) string {
hasher := md5.New()
_, err := hasher.Write([]byte(key))
if err != nil {
return EmptyStr
}
return hex.EncodeToString(hasher.Sum(nil))
}
func (ks *KeyStore) encrypt(data []byte, passphrase string) ([]byte, error) {
//Create a key based on the provided passphrase, 32 bytes required for AES.
key := ks.createHash(passphrase)
if key == EmptyStr {
return nil, errors.New("key store.encrypt: hash failed")
}
//Create a new AES block cipher based on the key above
block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, errors.New("Error creating AES block cipher: " + err.Error())
}
//Wrap block cipher in Galois Counter Mode
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, errors.New("error using Galois Counter Mode: " + err.Error())
}
//Creat a nonce compatible with GCM
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, errors.New("Error Creating nonce: " + err.Error())
}
//Prepend nonce to the cipher text to ensure the decrypt function uses the same nonce.
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext, nil
}
func (ks *KeyStore) decrypt(data []byte, passphrase string) ([]byte, error) {
//Create a key based on the provided passphrase, 32 bytes required for AES.
key := ks.createHash(passphrase)
if key == EmptyStr {
return nil, errors.New("KeyStore.encrypt: Hash failed")
}
//Create a new AES block cipher based on the key above
block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, errors.New("Error creating AES block cipher: " + err.Error())
}
//Wrap block cipher in Galois Counter Mode
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, errors.New("Error using Galois Counter Mode: " + err.Error())
}
//Get nonce from prefix of cipher text.
nonceSize := gcm.NonceSize()
nonce, cipherText := data[:nonceSize], data[nonceSize:]
//Decrypt file and return plain text.
plaintext, err := gcm.Open(nil, nonce, cipherText, nil)
if err != nil {
return nil, errors.New("Error decrypting: " + err.Error())
}
return plaintext, nil
}
func (ks *KeyStore) SaveKeyData(path string, address Address, data []byte, passphrase string) error {
filename, _ := filepath.Abs(path + buildFileName(address))
f, _ := os.Create(filename)
defer f.Close()
data, err := ks.encrypt(data, passphrase)
if err != nil {
return errors.New("error writing encrypted data to file:" + err.Error())
}
account := AccountKey{
Version: VERSION,
CipherText: hex.EncodeToString(data),
Address: address.Humanize(),
}
accData, err := json.Marshal(account)
if err != nil {
return err
}
f.Write(accData)
return nil
}
func (ks *KeyStore) GetKeyData(path string, address Address, passphrase string) ([]byte, error) {
accData := &AccountKey{}
filename, err := GetFileName(path, address)
if err != nil {
return nil, err
}
if !ks.KeyExists(path, address) {
return nil, errors.New("keystore: file doesn't exist")
}
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, accData)
if err != nil {
return nil, err
}
cipherData, err := hex.DecodeString(accData.CipherText)
if err != nil {
return nil, err
}
return ks.decrypt(cipherData, passphrase)
}
func (ks *KeyStore) DeleteKey(path string, address Address, passphrase string) error {
if res, err := ks.VerifyPassphrase(path, address, passphrase); !res {
if err != nil {
return err
}
return errors.New("error: invalid password")
}
filename, err := GetFileName(path, address)
if err != nil {
return err
}
err = os.Remove(filename)
if err != nil {
return err
}
return nil
}
func (ks *KeyStore) VerifyPassphrase(path string, address Address, passphrase string) (bool, error) {
_, err := ks.GetKeyData(path, address, passphrase)
if err != nil {
return false, err
}
return true, nil
}
func NewKeyStore() *KeyStore {
return &KeyStore{}
}
func (ks *KeyStore) KeyExists(path string, address Address) bool {
filename, err := GetFileName(path, address)
if err != nil {
return false
}
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func (ks *KeyStore) GetAddress(path string, filename string) (Address, error) {
accData := &AccountKey{}
address := Address{}
absPath, err := filepath.Abs(path + filename)
if err != nil {
return nil, err
}
data, err := ioutil.ReadFile(absPath)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, accData)
if err != nil {
return nil, err
}
err = address.UnmarshalText([]byte(accData.Address))
if err != nil {
return nil, err
}
return address, nil
}
func buildFileName(address Address) string {
t := time.Now()
zone, _ := t.Zone()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d.%03d%s",
t.Year(),
t.Month(),
t.Day(),
t.Hour(),
t.Minute(),
t.Second(),
t.Nanosecond(),
zone)
return "OL_" + formatted + "_" + address.Humanize()
}
func GetFileName(path string, address Address) (string, error) {
pattern, _ := filepath.Abs(path + "*" + address.Humanize())
matches, err := filepath.Glob(pattern)
if err != nil {
return "", err
}
if len(matches) != 1 {
return "", errors.New("invalid address")
}
return matches[0], nil
}