-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.go
102 lines (82 loc) · 1.89 KB
/
user.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
package main
import (
"crypto/ecdsa"
"encoding/json"
"io/ioutil"
"log"
"github.com/gtank/cryptopasta"
)
const (
// nBitsForKeypair sets the strength of keypair
nBitsForUserKeypair = 2048
)
type User struct {
PubKeyRaw string
PrivKeyRaw string
Alias string
PublicKey *ecdsa.PublicKey `json:"-"`
PrivateKey *ecdsa.PrivateKey `json:"-"`
}
func (u *User) GetPublicKey() (*ecdsa.PublicKey, error) {
if u.PublicKey == nil {
if err := u.LoadKeys(); err != nil {
return nil, err
}
}
return u.PublicKey, nil
}
func (u *User) GetPrivateKey() (*ecdsa.PrivateKey, error) {
if u.PrivateKey == nil {
if err := u.LoadKeys(); err != nil {
return nil, err
}
}
return u.PrivateKey, nil
}
func (u *User) LoadKeys() (err error) {
u.PrivateKey, err = cryptopasta.DecodePrivateKey([]byte(u.PrivKeyRaw))
if err != nil {
return err
}
u.PublicKey, err = cryptopasta.DecodePublicKey([]byte(u.PubKeyRaw))
return err
}
func NewUser(alias string) (*User, error) {
key, err := cryptopasta.NewSigningKey()
if err != nil {
return nil, err
}
pubKeyRaw, err := cryptopasta.EncodePublicKey(&key.PublicKey)
privKeyRaw, err := cryptopasta.EncodePrivateKey(key)
u := &User{
PubKeyRaw: string(pubKeyRaw),
PrivKeyRaw: string(privKeyRaw),
PrivateKey: key,
PublicKey: &key.PublicKey,
Alias: alias,
}
return u, nil
}
func CreateUserIfNotExists(path, alias string) (*User, error) {
if !Exists(path) {
user, err := NewUser("DefaultBob")
if err != nil {
log.Fatal("Cannot generate new User identity", err)
}
userConfJSON, _ := json.MarshalIndent(user, "", " ")
err = ioutil.WriteFile(MyUserConfPath, userConfJSON, 0644)
if err != nil {
return nil, err
}
}
file, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal("Cannot read user config", err)
}
var user User
err = json.Unmarshal(file, &user)
if err != nil {
return nil, err
}
return &user, nil
}