-
Notifications
You must be signed in to change notification settings - Fork 0
/
vault.go
78 lines (61 loc) · 1.58 KB
/
vault.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
package vault
import (
"encoding/hex"
"errors"
"fmt"
"os"
"regexp"
)
// ErrInvalidVaultFile is returned when the vault file is invalid
var ErrInvalidVaultFile = errors.New("invalid vault file")
var fileRegex = regexp.MustCompile(`(?m)^\$VAULT;1.0;AES256\n(?P<contents>[0-9a-f]+)$`)
// Vault is a simple key-value store with an interoperable backend.
type Vault struct {
Storage Storage
}
// NewVault creates a new vault using a Fs as the storage backend.
func NewVault(path string) (*Vault, error) {
_, err := os.Stat(path)
if err != nil {
return nil, err
}
return &Vault{
Storage: Fs(path),
}, nil
}
// Get retrieves the value of a key from the vault.
func (v *Vault) Get(key string, password []byte) ([]byte, error) {
bytes, err := v.Storage.Read(key)
if err != nil {
return nil, err
}
matches := fileRegex.FindAllStringSubmatch(string(bytes), -1)
if len(matches) != 1 {
return nil, ErrInvalidVaultFile
}
decoded, err := hex.DecodeString(matches[0][1])
if err != nil {
return nil, err
}
return decrypt(password, decoded)
}
// Set stores a value in the vault.
func (v *Vault) Set(key string, value []byte, password []byte) error {
encrypted, err := encrypt(password, value)
if err != nil {
return err
}
contents := fmt.Sprintf("$VAULT;1.0;AES256\n%x", encrypted)
return v.Storage.Write(
key,
[]byte(contents),
)
}
// Delete removes a key from the vault.
func (v *Vault) Delete(key string) error {
return v.Storage.Delete(key)
}
// Has returns true if the vault contains the given key.
func (v *Vault) Has(key string) bool {
return v.Storage.Has(key)
}