-
Notifications
You must be signed in to change notification settings - Fork 3
/
key.go
106 lines (98 loc) · 1.85 KB
/
key.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
package authb
import (
"encoding/json"
"fmt"
"github.com/nats-io/nkeys"
)
type Key struct {
Pair nkeys.KeyPair
Public string
Seed []byte
}
func (k *Key) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Key string `json:"key"`
}{
Key: string(k.Seed),
})
}
func (k *Key) UnmarshalJSON(data []byte) error {
var v struct {
Key string `json:"key"`
}
if err := json.Unmarshal(data, &v); err != nil {
return err
}
var err error
k.Seed = []byte(v.Key)
k.Pair, err = nkeys.FromSeed(k.Seed)
if err != nil {
return err
}
k.Public, err = k.Pair.PublicKey()
return err
}
func KeyFromNkey(kp nkeys.KeyPair, check ...nkeys.PrefixByte) (*Key, error) {
k := &Key{Pair: kp}
var err error
k.Public, err = kp.PublicKey()
if err != nil {
return nil, err
}
k.Seed, _ = kp.Seed()
if len(check) > 0 {
if err = nkeys.CompatibleKeyPair(kp, check...); err != nil {
return nil, err
}
}
return k, nil
}
func KeyFrom(key string, check ...nkeys.PrefixByte) (*Key, error) {
k := &Key{}
var err error
if len(key) == 0 {
return nil, fmt.Errorf("invalid key - empty string")
}
if key[0] == 'S' {
k.Pair, err = nkeys.FromSeed([]byte(key))
if err != nil {
return nil, err
}
k.Seed, err = k.Pair.Seed()
if err != nil {
return nil, err
}
} else {
k.Pair, err = nkeys.FromPublicKey(key)
if err != nil {
return nil, err
}
}
if len(check) > 0 {
if err = nkeys.CompatibleKeyPair(k.Pair, check...); err != nil {
return nil, err
}
}
k.Public, err = k.Pair.PublicKey()
if err != nil {
return nil, err
}
return k, nil
}
func KeyFor(p nkeys.PrefixByte) (*Key, error) {
k := &Key{}
var err error
k.Pair, err = nkeys.CreatePair(p)
if err != nil {
return k, err
}
k.Seed, err = k.Pair.Seed()
if err != nil {
return k, err
}
k.Public, err = k.Pair.PublicKey()
if err != nil {
return k, err
}
return k, nil
}