-
Notifications
You must be signed in to change notification settings - Fork 32
/
publickey.go
103 lines (80 loc) · 1.97 KB
/
publickey.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
package prefs
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"github.com/manifoldco/go-base64"
"github.com/manifoldco/torus-cli/data"
"github.com/manifoldco/torus-cli/errs"
)
const requiredPermissions = 0700
// PublicKey is en ed25519 public key.
type PublicKey struct {
PublicKey base64.Value `json:"public_key"`
}
// LoadPublicKey reads the publickey file from disk and parses the json
func LoadPublicKey(prefs *Preferences) (*PublicKey, error) {
filePath := prefs.Core.PublicKeyFile
var fd io.Reader
var err error
if filePath == "" {
var b []byte
b, err = data.Asset("data/public_key.json")
if err == nil {
fd = bytes.NewReader(b)
}
} else {
fd, err = readPublicKeyFile(filePath)
}
if err != nil {
return nil, err
}
key, err := parsePublicKeyFile(fd)
if err != nil {
return nil, err
}
return key, nil
}
func readPublicKeyFile(filePath string) (*os.File, error) {
fd, err := os.Open(filePath)
if os.IsNotExist(err) {
return nil, fmt.Errorf("error: could not locate public key file: %s", filePath)
}
if err != nil {
return nil, err
}
return fd, nil
}
func parsePublicKeyFile(fd io.Reader) (*PublicKey, error) {
key := &PublicKey{}
dec := json.NewDecoder(fd)
err := dec.Decode(key)
if err != nil {
return nil, err
}
return key, nil
}
// ValidatePublicKey checks the publickey path for valid file
func ValidatePublicKey(filePath string) error {
var text string
src, err := os.Stat(filePath)
if err != nil {
return errs.NewExitError("Publick key file must exist")
}
fMode := src.Mode()
if fMode.Perm() != requiredPermissions {
text = fmt.Sprintf("File specified has permissions %d, must have permissions %d", fMode.Perm(), requiredPermissions)
return errs.NewExitError(text)
}
fd, err := readPublicKeyFile(filePath)
if err != nil {
return errs.NewExitError("Could not read file, permissions ok")
}
_, err = parsePublicKeyFile(fd)
if err != nil {
return errs.NewExitError("Could not parse JSON")
}
return nil
}