Skip to content
Open
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
6 changes: 6 additions & 0 deletions crypto/ecies/ecies.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ func (prv *PrivateKey) GenerateShared(pub *PublicKey, skLen, macLen int) (sk []b
if prv.PublicKey.Curve != pub.Curve {
return nil, ErrInvalidCurve
}
if pub.X == nil || pub.Y == nil || !pub.Curve.IsOnCurve(pub.X, pub.Y) {
return nil, ErrInvalidPublicKey
}
if skLen+macLen > MaxSharedKeyLength(pub) {
return nil, ErrSharedKeyTooBig
}
Expand Down Expand Up @@ -308,6 +311,9 @@ func (prv *PrivateKey) Decrypt(c, s1, s2 []byte) (m []byte, err error) {
if R.X == nil {
return nil, ErrInvalidPublicKey
}
if !R.Curve.IsOnCurve(R.X, R.Y) {
return nil, ErrInvalidPublicKey
}

z, err := prv.GenerateShared(R, params.KeyLen, params.KeyLen)
if err != nil {
Expand Down
39 changes: 39 additions & 0 deletions crypto/ecies/ecies_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,45 @@ func TestSharedKeyStatic(t *testing.T) {
}
}

// TestInvalidCurve verifies that off-curve public keys are rejected early
// in both GenerateShared and Decrypt, preventing invalid curves
// (go-ethereum#33669).
func TestInvalidCurve(t *testing.T) {
prv, err := GenerateKey(rand.Reader, crypto.S256(), nil)
if err != nil {
t.Fatal(err)
}

// Construct an off-curve public key: secp256k1 generator X but Y+1.
// This point does not satisfy the curve equation y² = x³ + 7 (mod p).
offCurvePub := &PublicKey{
Curve: crypto.S256(),
X: new(big.Int).Set(crypto.S256().Params().Gx),
Y: new(big.Int).Add(crypto.S256().Params().Gy, big.NewInt(1)),
}

// GenerateShared must reject the off-curve point before performing ECDH.
skLen := MaxSharedKeyLength(&prv.PublicKey) / 2
_, err = prv.GenerateShared(offCurvePub, skLen, skLen)
if err != ErrInvalidPublicKey {
t.Fatalf("GenerateShared: expected ErrInvalidPublicKey, got %v", err)
}

// Decrypt must reject a ciphertext whose embedded ephemeral key is off-curve.
// Format: [0x04 | X (32B) | Y (32B) | 1B ciphertext | 32B MAC] = 98 bytes.
ct := make([]byte, 98)
ct[0] = 4 // uncompressed point prefix
offCurvePub.X.FillBytes(ct[1:33])
offCurvePub.Y.FillBytes(ct[33:65])
// ct[65] = 0x00 (dummy ciphertext byte)
// ct[66:98] = zeros (dummy MAC, never reached)

_, err = prv.Decrypt(ct, nil, nil)
if err != ErrInvalidPublicKey {
t.Fatalf("Decrypt: expected ErrInvalidPublicKey, got %v", err)
}
}

func hexKey(prv string) *PrivateKey {
key, err := crypto.HexToECDSA(prv)
if err != nil {
Expand Down
Loading