-
Notifications
You must be signed in to change notification settings - Fork 0
/
keypair.go
127 lines (110 loc) · 2.32 KB
/
keypair.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package bls
import (
"crypto/rand"
"errors"
"math/big"
"golang.org/x/crypto/sha3"
)
var maxUint256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil)
func randBytes32() []byte {
x, _ := rand.Int(rand.Reader, maxUint256)
buf := make([]byte, 32)
copy(buf[32-len(x.Bytes()):], x.Bytes())
return buf
}
type KeyPair struct {
private *PrivateKey
public *PublicKey
}
func GenerateKey() *KeyPair {
kp := new(KeyPair)
kp.private = new(PrivateKey)
kp.private.Unmarshal(randBytes32())
kp.public = Private2Public(kp.private)
return kp
}
func KeyFromSeed(seed []byte) *KeyPair {
kp := new(KeyPair)
kp.private = new(PrivateKey)
h := sha3.Sum256(seed)
kp.private.Unmarshal(h[:])
kp.public = Private2Public(kp.private)
return kp
}
func (kp *KeyPair) fixPrivate() {
kp.private = new(PrivateKey).Null()
}
func (kp *KeyPair) Private() *PrivateKey {
if kp.private == nil {
kp.fixPrivate()
}
ret := new(PrivateKey)
ret.Unmarshal(kp.private.Marshal())
return ret
}
func (kp *KeyPair) MarshalPrivate() []byte {
if kp.private == nil {
kp.fixPrivate()
}
return kp.private.Marshal()
}
func (kp *KeyPair) UnmarshalPrivate(in []byte) error {
if kp.private == nil {
kp.private = new(PrivateKey)
}
if err := kp.private.Unmarshal(in); err != nil {
return err
}
kp.public = Private2Public(kp.private)
return nil
}
func (kp *KeyPair) fixPublic() {
kp.public = new(PublicKey).Null()
if kp.private == nil {
kp.fixPrivate()
}
if !kp.private.IsNull() {
kp.public = Private2Public(kp.private)
}
}
func (kp *KeyPair) Public() *PublicKey {
if kp.public == nil {
kp.fixPublic()
}
ret := new(PublicKey)
ret.Unmarshal(kp.public.Marshal())
return ret
}
func (kp *KeyPair) MarshalPublic() []byte {
if kp.public == nil {
kp.fixPublic()
}
return kp.public.Marshal()
}
func (kp *KeyPair) UnmarshalPublic(in []byte) error {
kp.private = new(PrivateKey).Null()
if kp.public == nil {
kp.public = new(PublicKey)
}
return kp.public.Unmarshal(in)
}
func (kp *KeyPair) Marshal() []byte {
if kp.private == nil {
kp.fixPrivate()
}
if kp.private.IsNull() {
return kp.MarshalPublic()
}
return kp.MarshalPrivate()
}
func (kp *KeyPair) Unmarshal(in []byte) error {
switch len(in) {
case 32:
kp.UnmarshalPrivate(in)
case 128:
kp.UnmarshalPublic(in)
default:
return errors.New("invalid length of key pair")
}
return nil
}