Skip to content

Commit 1a32bdf

Browse files
authored
crypto: fix error check in toECDSA (#15632)
With this change, key, err := crypto.HexToECDSA("000000...") returns nil key and an error instead of a non-nil key with nil X and Y inside. Issue found by @guidovranken.
1 parent 2499b1b commit 1a32bdf

2 files changed

Lines changed: 12 additions & 0 deletions

File tree

‎crypto/crypto.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
9898
}
9999
priv.D = new(big.Int).SetBytes(d)
100100
priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
101+
if priv.PublicKey.X == nil {
102+
return nil, errors.New("invalid private key")
103+
}
101104
return priv, nil
102105
}
103106

‎crypto/crypto_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,15 @@ func TestKeccak256Hash(t *testing.T) {
4040
checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Keccak256Hash(in); return h[:] }, msg, exp)
4141
}
4242

43+
func TestToECDSAErrors(t *testing.T) {
44+
if _, err := HexToECDSA("0000000000000000000000000000000000000000000000000000000000000000"); err == nil {
45+
t.Fatal("HexToECDSA should've returned error")
46+
}
47+
if _, err := HexToECDSA("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); err == nil {
48+
t.Fatal("HexToECDSA should've returned error")
49+
}
50+
}
51+
4352
func BenchmarkSha3(b *testing.B) {
4453
a := []byte("hello world")
4554
for i := 0; i < b.N; i++ {

0 commit comments

Comments
 (0)