-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathkeys.go
84 lines (66 loc) · 2.44 KB
/
keys.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
package noise
import (
"encoding/hex"
"encoding/json"
"github.com/oasislabs/ed25519"
"io"
)
const (
// SizePublicKey is the size in bytes of a nodes/peers public key.
SizePublicKey = ed25519.PublicKeySize
// SizePrivateKey is the size in bytes of a nodes/peers private key.
SizePrivateKey = ed25519.PrivateKeySize
)
type (
// PublicKey is the default node/peer public key type.
PublicKey [SizePublicKey]byte
// PrivateKey is the default node/peer private key type.
PrivateKey [SizePrivateKey]byte
)
var (
// ZeroPublicKey is the zero-value for a node/peer public key.
ZeroPublicKey PublicKey
// ZeroPrivateKey is the zero-value for a node/peer private key.
ZeroPrivateKey PrivateKey
)
// GenerateKeys randomly generates a new pair of cryptographic keys. Nil may be passed to rand in order to use
// crypto/rand by default. It throws an error if rand is invalid.
func GenerateKeys(rand io.Reader) (publicKey PublicKey, privateKey PrivateKey, err error) {
pub, priv, err := ed25519.GenerateKey(rand)
if err != nil {
return publicKey, privateKey, err
}
copy(publicKey[:], pub)
copy(privateKey[:], priv)
return publicKey, privateKey, nil
}
// Verify returns true if the cryptographic signature of data is representative of this public key.
func (k PublicKey) Verify(data, signature []byte) bool {
return ed25519.Verify(k[:], data, signature)
}
// String returns the hexadecimal representation of this public key.
func (k PublicKey) String() string {
return hex.EncodeToString(k[:])
}
// MarshalJSON returns the hexadecimal representation of this public key in JSON. It should never throw an error.
func (k PublicKey) MarshalJSON() ([]byte, error) {
return json.Marshal(k.String())
}
// Sign uses this private key to sign data and return its cryptographic signature as a slice of bytes.
func (k PrivateKey) Sign(data []byte) []byte {
return ed25519.Sign(k[:], data)
}
// String returns the hexadecimal representation of this private key.
func (k PrivateKey) String() string {
return hex.EncodeToString(k[:])
}
// MarshalJSON returns the hexadecimal representation of this private key in JSON. It should never throw an error.
func (k PrivateKey) MarshalJSON() ([]byte, error) {
return json.Marshal(hex.EncodeToString(k[:]))
}
// Public returns the public key associated to this private key.
func (k PrivateKey) Public() PublicKey {
var publicKey PublicKey
copy(publicKey[:], (ed25519.PrivateKey)(k[:]).Public().(ed25519.PublicKey))
return publicKey
}