forked from libp2p/go-libp2p-crypto
/
secp256k1.go
107 lines (83 loc) · 2.4 KB
/
secp256k1.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
package crypto
import (
"fmt"
"io"
btcec "github.com/btcsuite/btcd/btcec"
pb "github.com/libp2p/go-libp2p-crypto/pb"
sha256 "github.com/minio/sha256-simd"
)
type Secp256k1PrivateKey btcec.PrivateKey
type Secp256k1PublicKey btcec.PublicKey
func GenerateSecp256k1Key(src io.Reader) (PrivKey, PubKey, error) {
privk, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return nil, nil, err
}
k := (*Secp256k1PrivateKey)(privk)
return k, k.GetPublic(), nil
}
func UnmarshalSecp256k1PrivateKey(data []byte) (PrivKey, error) {
if len(data) != btcec.PrivKeyBytesLen {
return nil, fmt.Errorf("expected secp256k1 data size to be %d", btcec.PrivKeyBytesLen)
}
privk, _ := btcec.PrivKeyFromBytes(btcec.S256(), data)
return (*Secp256k1PrivateKey)(privk), nil
}
func UnmarshalSecp256k1PublicKey(data []byte) (PubKey, error) {
k, err := btcec.ParsePubKey(data, btcec.S256())
if err != nil {
return nil, err
}
return (*Secp256k1PublicKey)(k), nil
}
func (sk *Secp256k1PrivateKey) Type() pb.KeyType {
return pb.KeyType_Secp256k1
}
func (sk *Secp256k1PrivateKey) Bytes() ([]byte, error) {
return MarshalPrivateKey(sk)
}
func (k *Secp256k1PrivateKey) Raw() ([]byte, error) {
return (*btcec.PrivateKey)(k).Serialize(), nil
}
func (k *Secp256k1PrivateKey) Equals(o Key) bool {
sk, ok := o.(*Secp256k1PrivateKey)
if !ok {
return false
}
return k.D.Cmp(sk.D) == 0
}
func (k *Secp256k1PrivateKey) Sign(data []byte) ([]byte, error) {
hash := sha256.Sum256(data)
sig, err := (*btcec.PrivateKey)(k).Sign(hash[:])
if err != nil {
return nil, err
}
return sig.Serialize(), nil
}
func (k *Secp256k1PrivateKey) GetPublic() PubKey {
return (*Secp256k1PublicKey)((*btcec.PrivateKey)(k).PubKey())
}
func (sk *Secp256k1PublicKey) Type() pb.KeyType {
return pb.KeyType_Secp256k1
}
func (sk *Secp256k1PublicKey) Bytes() ([]byte, error) {
return MarshalPublicKey(sk)
}
func (k *Secp256k1PublicKey) Raw() ([]byte, error) {
return (*btcec.PublicKey)(k).SerializeCompressed(), nil
}
func (k *Secp256k1PublicKey) Equals(o Key) bool {
sk, ok := o.(*Secp256k1PublicKey)
if !ok {
return false
}
return (*btcec.PublicKey)(k).IsEqual((*btcec.PublicKey)(sk))
}
func (k *Secp256k1PublicKey) Verify(data []byte, sigStr []byte) (bool, error) {
sig, err := btcec.ParseDERSignature(sigStr, btcec.S256())
if err != nil {
return false, err
}
hash := sha256.Sum256(data)
return sig.Verify(hash[:], (*btcec.PublicKey)(k)), nil
}