Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 4 additions & 13 deletions publickey.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import (
"crypto/elliptic"
"crypto/subtle"
"encoding/hex"
"math/big"

"github.com/fomichev/secp256k1"
"github.com/pkg/errors"
"math/big"
)

// PublicKey instance with nested elliptic.Curve interface (secp256k1 instance in our case)
Expand Down Expand Up @@ -101,12 +102,7 @@ func NewPublicKeyFromBytes(b []byte) (*PublicKey, error) {
// Bytes returns public key raw bytes;
// Could be optionally compressed by dropping Y part
func (k *PublicKey) Bytes(compressed bool) []byte {
x := k.X.Bytes()
if len(x) < 32 {
for i := 0; i < 32-len(x); i++ {
x = append([]byte{0}, x...)
}
}
x := zeroPad(k.X.Bytes(), 32)

if compressed {
// If odd
Expand All @@ -118,12 +114,7 @@ func (k *PublicKey) Bytes(compressed bool) []byte {
return bytes.Join([][]byte{{0x02}, x}, nil)
}

y := k.Y.Bytes()
if len(y) < 32 {
for i := 0; i < 32-len(y); i++ {
y = append([]byte{0}, y...)
}
}
y := zeroPad(k.Y.Bytes(), 32)

return bytes.Join([][]byte{{0x04}, x, y}, nil)
}
Expand Down
11 changes: 10 additions & 1 deletion publickey_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package go_eccrypto

import (
"github.com/stretchr/testify/assert"
"encoding/hex"
"testing"

"github.com/stretchr/testify/assert"
)

func TestPublicKey_Equals(t *testing.T) {
Expand All @@ -13,3 +15,10 @@ func TestPublicKey_Equals(t *testing.T) {

assert.True(t, privkey.PublicKey.Equals(privkey.PublicKey))
}

func TestSerialization(t *testing.T) {
// PubKey where y starts with 0000.
p, _ := hex.DecodeString("04f17021dd606fe48530d467f21211e82810438b932432b4f9d8ae03d899f237020000aff977375ae853bb349dff793442d4fabb7d05a64f02e8c6d2ca53db5df2")
pubkey, _ := NewPublicKeyFromBytes(p)
assert.Equal(t, p, pubkey.Bytes(false))
}
13 changes: 8 additions & 5 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package go_eccrypto

import (
"crypto/sha256"
"io"

"github.com/pkg/errors"
"golang.org/x/crypto/hkdf"
"io"
)

func kdf(secret []byte) (key []byte, err error) {
Expand All @@ -17,10 +18,12 @@ func kdf(secret []byte) (key []byte, err error) {
return key, nil
}

func zeroPad(b []byte, leigth int) []byte {
for i := 0; i < leigth-len(b); i++ {
b = append([]byte{0x00}, b...)
func zeroPad(b []byte, length int) []byte {
if len(b) >= length {
return b
}

return b
padded := make([]byte, length)
copy(padded[length-len(b):], b)
return padded
}