Skip to content

Commit

Permalink
Fix broken zero pad implementation causing corrupted ciphertext (#87)
Browse files Browse the repository at this point in the history
* fix: bug in zeroPad implementation

* fix: replaced broken, duplicate zeroPad code

* test: added benchmark that would make #86 more obvious
  • Loading branch information
gmaiainc authored Dec 14, 2023
1 parent c6e7751 commit 0169652
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
16 changes: 16 additions & 0 deletions ecies_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,19 @@ func TestEncryptAgainstPythonVersion(t *testing.T) {

assert.Equal(t, string(plaintext), testingMessage)
}

func BenchmarkEncryptAndDecrypt(b *testing.B) {
privkey := NewPrivateKeyFromBytes(testingReceiverPrivkey)

for i := 0; i < b.N; i++ {
ciphertext, err := Encrypt(privkey.PublicKey, []byte(testingMessage))
if err != nil {
b.Fatal(err)
}

_, err = Decrypt(privkey, ciphertext)
if err != nil {
b.Fatal(err)
}
}
}
12 changes: 2 additions & 10 deletions publickey.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,7 @@ func NewPublicKeyFromBytes(b []byte) (*PublicKey, error) {
// 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(x, 32)

if compressed {
// If odd
Expand All @@ -120,11 +116,7 @@ func (k *PublicKey) Bytes(compressed bool) []byte {
}

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

return bytes.Join([][]byte{{0x04}, x, y}, nil)
}
Expand Down
10 changes: 6 additions & 4 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,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 {
panic("bytes too long")
}
if len(b) < length {
b = append(make([]byte, length-len(b)), b...)
}

return b
}

0 comments on commit 0169652

Please sign in to comment.