forked from Qarik-Group/safe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
secret.go
87 lines (73 loc) · 2.07 KB
/
secret.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
package vault
import (
"encoding/json"
"github.com/ghodss/yaml"
)
// A Secret contains a set of key/value pairs that store anything you
// want, including passwords, RSAKey keys, usernames, etc.
type Secret struct {
data map[string] string
}
func NewSecret() *Secret {
return &Secret{ make(map[string] string) }
}
func (s Secret) MarshalJSON() ([]byte, error) {
return json.Marshal(s.data)
}
func (s *Secret) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, &s.data)
}
// Has returns true if the Secret has defined the given key.
func (s *Secret) Has(key string) bool {
_, ok := s.data[key]
return ok
}
// Get retrieves the value of the given key, or "" if no such key exists.
func (s *Secret) Get(key string) string {
x, _ := s.data[key]
return x
}
// Set stores a value in the Secret, under the given key.
func (s *Secret) Set(key, value string) {
s.data[key] = value
}
// Password creates and stores a new randomized password.
func (s *Secret) Password(key string, length int) {
s.data[key] = random(length)
}
func (s *Secret) keypair(private, public string, err error) error {
if err != nil {
return err
}
s.data["private"] = private
s.data["public"] = public
return nil
}
// RSAKey generates a new public/private keypair, and stores
// it in the secret, under the 'public' and 'private' keys.
func (s *Secret) RSAKey(bits int) error {
return s.keypair(rsakey(bits))
}
// SSHKey generates a new public/private keypair, and stores
// it in the secret, under the 'public' and 'private' keys.
func (s *Secret) SSHKey(bits int) error {
return s.keypair(sshkey(bits))
}
// JSON converts a Secret to its JSON representation and returns it as a string.
// Returns an empty string if there were any errors.
func (s *Secret) JSON() string {
b, err := json.Marshal(s.data)
if err != nil {
return ""
}
return string(b)
}
// YAML converts a Secret to its YAML representation and returns it as a string.
// Returns an empty string if there were any errors.
func (s *Secret) YAML() string {
b, err := yaml.Marshal(s.data)
if err != nil {
return ""
}
return string(b)
}