-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathkeyring.go
84 lines (69 loc) · 1.55 KB
/
keyring.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
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
)
type keyRing interface {
Load() error
Save() error
AddKey(name string, keyID []byte, key []byte)
Key(keyID []byte) ([]byte, error)
}
type fileKeyRing struct {
fileName string
KeyEntries []keyEntry
}
type keyEntry struct {
Description string `yaml:"description"`
KeyID string `yaml:"key-id"`
Key string `yaml:"key"`
}
func (kr *fileKeyRing) AddKey(desc string, keyID []byte, key []byte) {
kr.KeyEntries = append(kr.KeyEntries, keyEntry{
Description: desc,
KeyID: string(encode(keyID[:])),
Key: string(encode(key[:])),
})
}
func (kr *fileKeyRing) Key(keyID []byte) ([]byte, error) {
b64 := string(encode(keyID[:]))
for _, ke := range kr.KeyEntries {
if ke.KeyID == b64 {
dec, err := decode([]byte(ke.Key))
if err != nil {
return []byte{}, err
}
if len(dec) != 32 {
return []byte{}, fmt.Errorf("unexpected length of key: %d", len(dec))
}
return dec, nil
}
}
return []byte{}, errKeyNotFound
}
func (kr *fileKeyRing) Load() error {
bytes, err := os.ReadFile(kr.fileName)
if err != nil {
return err
}
err = yaml.Unmarshal(bytes, kr)
return err
}
func (kr *fileKeyRing) Save() error {
ser, err := yaml.Marshal(kr)
if err != nil {
log.Fatal(err)
}
path := filepath.Dir(kr.fileName)
_, err = os.Stat(path)
if os.IsNotExist(err) {
err := os.MkdirAll(path, 0700)
if err != nil {
return fmt.Errorf("error creating strongbox home folder: %s", err)
}
}
return os.WriteFile(kr.fileName, ser, 0600)
}