-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.go
112 lines (98 loc) · 1.77 KB
/
data.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
package main
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"path/filepath"
)
type Data struct {
Default string
Accounts map[string]string
Lengths map[string]int
}
func load() *Data {
dir, err := os.UserHomeDir()
if err != nil {
log.Fatalln(err)
}
f, err := os.Open(filepath.Join(dir, ".pwgen"))
if err != nil {
if os.IsNotExist(err) {
return &Data{Accounts: map[string]string{}, Lengths: map[string]int{}}
}
log.Fatalln(err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
log.Fatalln(err)
}
v, err := AesDecrypt(data)
if err != nil {
log.Fatalln(err)
}
m := &Data{Accounts: map[string]string{}, Lengths: map[string]int{}}
err = json.Unmarshal(v, &m)
if err != nil {
log.Fatalln(err)
}
return m
}
func save(m *Data) {
data, err := json.Marshal(m)
if err != nil {
log.Fatalln(err)
}
data, err = AesEncrypt(data)
if err != nil {
log.Fatalln(err)
}
dir, err := os.UserHomeDir()
if err != nil {
log.Fatalln(err)
}
f, err := os.OpenFile(filepath.Join(dir, ".pwgen"), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
log.Fatalln(err)
}
defer f.Close()
_, err = f.Write(data)
if err != nil {
log.Fatalln(err)
}
}
func getKey(name string) string {
data := load()
accounts := data.Accounts
if len(accounts) > 0 {
return accounts[name]
}
return ""
}
func setKey(name, secret string, isDefault bool) {
m := load()
m.Accounts[name] = secret
if isDefault {
m.Default = name
}
save(m)
}
func setLength(hostname string, l int) {
m := load()
m.Lengths[hostname] = l
save(m)
}
func getLength(hostname string) int {
m := load()
return m.Lengths[hostname]
}
func delKey(name string) {
m := load()
delete(m.Accounts, name)
delete(m.Lengths, name)
if m.Default == name {
m.Default = ""
}
save(m)
}