This repository has been archived by the owner on May 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 346
/
key.go
94 lines (81 loc) · 2.25 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
package mock
import (
"crypto/rand"
"encoding/json"
"github.com/hyperledger/burrow/acm"
"github.com/hyperledger/burrow/crypto"
"github.com/pkg/errors"
"golang.org/x/crypto/ed25519"
)
// Mock ed25510 key for mock keys client
// Simple ed25519 key structure for mock purposes with ripemd160 address
type Key struct {
Name string
Address crypto.Address
PublicKey []byte
PrivateKey []byte
}
func newKey(name string) (*Key, error) {
key := &Key{
Name: name,
PublicKey: make([]byte, ed25519.PublicKeySize),
PrivateKey: make([]byte, ed25519.PrivateKeySize),
}
// this is a mock key, so the entropy of the source is purely
// for testing
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
copy(key.PrivateKey[:], privateKey[:])
copy(key.PublicKey[:], publicKey[:])
pk, err := crypto.PublicKeyFromBytes(publicKey, crypto.CurveTypeEd25519)
if err != nil {
return nil, err
}
key.Address, err = crypto.AddressFromBytes(pk.GetAddress().Bytes())
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
if key.Name == "" {
key.Name = key.Address.String()
}
return key, nil
}
func mockKeyFromPrivateAccount(privateAccount *acm.PrivateAccount) *Key {
key := &Key{
Name: privateAccount.GetAddress().String(),
Address: privateAccount.GetAddress(),
PublicKey: privateAccount.GetPublicKey().PublicKey,
PrivateKey: privateAccount.PrivateKey().PrivateKey,
}
return key
}
func (key *Key) Sign(message []byte) (*crypto.Signature, error) {
return crypto.SignatureFromBytes(ed25519.Sign(key.PrivateKey, message), crypto.CurveTypeEd25519)
}
type PrivateKeyplainKeyJSON struct {
Plain []byte
}
// TODO: remove after merging keys taken from there to match serialisation
type plainKeyJSON struct {
Type string
Address string
PrivateKey PrivateKeyplainKeyJSON
}
// Returns JSON string compatible with that stored by monax-keys
func (key *Key) MonaxKeysJSON() string {
jsonKey := plainKeyJSON{
Address: key.Address.String(),
Type: "ed25519",
PrivateKey: PrivateKeyplainKeyJSON{Plain: key.PrivateKey},
}
bs, err := json.Marshal(jsonKey)
if err != nil {
return errors.Wrap(err, "could not create monax key json").Error()
}
return string(bs)
}