File tree Expand file tree Collapse file tree 3 files changed +22
-19
lines changed
Expand file tree Collapse file tree 3 files changed +22
-19
lines changed Original file line number Diff line number Diff line change @@ -5,9 +5,10 @@ import (
55 "crypto/elliptic"
66 "crypto/subtle"
77 "encoding/hex"
8+ "math/big"
9+
810 "github.com/fomichev/secp256k1"
911 "github.com/pkg/errors"
10- "math/big"
1112)
1213
1314// PublicKey instance with nested elliptic.Curve interface (secp256k1 instance in our case)
@@ -101,12 +102,7 @@ func NewPublicKeyFromBytes(b []byte) (*PublicKey, error) {
101102// Bytes returns public key raw bytes;
102103// Could be optionally compressed by dropping Y part
103104func (k * PublicKey ) Bytes (compressed bool ) []byte {
104- x := k .X .Bytes ()
105- if len (x ) < 32 {
106- for i := 0 ; i < 32 - len (x ); i ++ {
107- x = append ([]byte {0 }, x ... )
108- }
109- }
105+ x := zeroPad (k .X .Bytes (), 32 )
110106
111107 if compressed {
112108 // If odd
@@ -118,12 +114,7 @@ func (k *PublicKey) Bytes(compressed bool) []byte {
118114 return bytes .Join ([][]byte {{0x02 }, x }, nil )
119115 }
120116
121- y := k .Y .Bytes ()
122- if len (y ) < 32 {
123- for i := 0 ; i < 32 - len (y ); i ++ {
124- y = append ([]byte {0 }, y ... )
125- }
126- }
117+ y := zeroPad (k .Y .Bytes (), 32 )
127118
128119 return bytes .Join ([][]byte {{0x04 }, x , y }, nil )
129120}
Original file line number Diff line number Diff line change 11package go_eccrypto
22
33import (
4- "github.com/stretchr/testify/assert "
4+ "encoding/hex "
55 "testing"
6+
7+ "github.com/stretchr/testify/assert"
68)
79
810func TestPublicKey_Equals (t * testing.T ) {
@@ -13,3 +15,10 @@ func TestPublicKey_Equals(t *testing.T) {
1315
1416 assert .True (t , privkey .PublicKey .Equals (privkey .PublicKey ))
1517}
18+
19+ func TestSerialization (t * testing.T ) {
20+ // PubKey where y starts with 0000.
21+ p , _ := hex .DecodeString ("04f17021dd606fe48530d467f21211e82810438b932432b4f9d8ae03d899f237020000aff977375ae853bb349dff793442d4fabb7d05a64f02e8c6d2ca53db5df2" )
22+ pubkey , _ := NewPublicKeyFromBytes (p )
23+ assert .Equal (t , p , pubkey .Bytes (false ))
24+ }
Original file line number Diff line number Diff line change @@ -2,9 +2,10 @@ package go_eccrypto
22
33import (
44 "crypto/sha256"
5+ "io"
6+
57 "github.com/pkg/errors"
68 "golang.org/x/crypto/hkdf"
7- "io"
89)
910
1011func kdf (secret []byte ) (key []byte , err error ) {
@@ -17,10 +18,12 @@ func kdf(secret []byte) (key []byte, err error) {
1718 return key , nil
1819}
1920
20- func zeroPad (b []byte , leigth int ) []byte {
21- for i := 0 ; i < leigth - len (b ); i ++ {
22- b = append ([] byte { 0x00 }, b ... )
21+ func zeroPad (b []byte , length int ) []byte {
22+ if len (b ) >= length {
23+ return b
2324 }
2425
25- return b
26+ padded := make ([]byte , length )
27+ copy (padded [length - len (b ):], b )
28+ return padded
2629}
You can’t perform that action at this time.
0 commit comments