/
keys.go
110 lines (92 loc) · 2.42 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
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
package common
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/base64"
"errors"
"math/big"
)
type (
// PrivateKey is a private key wrapper.
PrivateKey ecdsa.PrivateKey
// PublicKey is a public key wrapper.
PublicKey ecdsa.PublicKey
)
// Public returns public part of key.
func (key *PrivateKey) Public() *PublicKey {
return (*PublicKey)(&key.PublicKey)
}
// Sign signs with key.
func (key *PrivateKey) Sign(hash []byte) (r, s *big.Int, err error) {
return ecdsa.Sign(rand.Reader, (*ecdsa.PrivateKey)(key), hash)
}
// Verify verifies the signatures.
func (pub *PublicKey) Verify(hash []byte, r, s *big.Int) bool {
return ecdsa.Verify((*ecdsa.PublicKey)(pub), hash, r, s)
}
// Bytes encodes public key to bytes.
func (pub *PublicKey) Bytes() []byte {
if pub == nil || pub.X == nil || pub.Y == nil {
return nil
}
return elliptic.Marshal(elliptic.P256(), pub.X, pub.Y)
}
// Base64 encodes public key to base64.
func (pub *PublicKey) Base64() string {
buf := pub.Bytes()
return base64.StdEncoding.EncodeToString(buf)
}
// BytesToPubkey decodes public key from bytes.
func BytesToPubkey(pub []byte) *PublicKey {
if len(pub) == 0 {
return nil
}
x, y := elliptic.Unmarshal(elliptic.P256(), pub)
return &PublicKey{Curve: elliptic.P256(), X: x, Y: y}
}
// Base64ToPubkey decodes public key from base64.
func Base64ToPubkey(s string) (*PublicKey, error) {
buf, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return nil, err
}
key := BytesToPubkey(buf)
if key == nil {
return nil, errors.New("pubkey is invalid")
}
return key, nil
}
/*
* Utils:
*/
// ToECDSAPub convert to ECDSA public key from bytes.
// NOTE: deprecated
func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
if len(pub) == 0 {
return nil
}
x, y := elliptic.Unmarshal(elliptic.P256(), pub)
return &ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y}
}
// FromECDSAPub create bytes from ECDSA public key.
// NOTE: deprecated
func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
if pub == nil || pub.X == nil || pub.Y == nil {
return nil
}
return elliptic.Marshal(elliptic.P256(), pub.X, pub.Y)
}
// StringToPubkey decode public key from base64 to common.PublicKey
// NOTE: deprecated
func StringToPubkey(pub string) (*PublicKey, error) {
bb, err := base64.StdEncoding.DecodeString(pub)
if err != nil {
return nil, err
}
key := BytesToPubkey(bb)
if key == nil {
return nil, errors.New("pubkey is invalid")
}
return key, nil
}