From 84fec407da1ab5d5756f72c5346cf00f96c00c64 Mon Sep 17 00:00:00 2001 From: Matthias Geihs Date: Tue, 7 Oct 2025 17:20:50 +0200 Subject: [PATCH] Fix pub key padding --- publickey.go | 17 ++++------------- publickey_test.go | 11 ++++++++++- utils.go | 13 ++++++++----- 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/publickey.go b/publickey.go index bd74a5e..90e15ad 100644 --- a/publickey.go +++ b/publickey.go @@ -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) @@ -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 @@ -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) } diff --git a/publickey_test.go b/publickey_test.go index 21e0100..aa40f8c 100644 --- a/publickey_test.go +++ b/publickey_test.go @@ -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) { @@ -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)) +} diff --git a/utils.go b/utils.go index bac3b59..cb82edc 100644 --- a/utils.go +++ b/utils.go @@ -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) { @@ -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 }