From bd1d6c9148bdb2feb9c96a85f284508cd1bc1dd4 Mon Sep 17 00:00:00 2001 From: Conner Fromknecht Date: Tue, 29 May 2018 17:06:32 -0700 Subject: [PATCH] btcec/pubkey: verify decompressed y-coord is sqroot --- btcec/pubkey.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/btcec/pubkey.go b/btcec/pubkey.go index b7491771..cf498075 100644 --- a/btcec/pubkey.go +++ b/btcec/pubkey.go @@ -32,8 +32,9 @@ func decompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, erro x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) x3.Add(x3, curve.Params().B) + x3.Mod(x3, curve.Params().P) - // now calculate sqrt mod p of x2 + B + // Now calculate sqrt mod p of x^3 + B // This code used to do a full sqrt based on tonelli/shanks, // but this was replaced by the algorithms referenced in // https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294 @@ -42,9 +43,19 @@ func decompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, erro if ybit != isOdd(y) { y.Sub(curve.Params().P, y) } + + // Check that y is a square root of x^3 + B. + y2 := new(big.Int).Mul(y, y) + y2.Mod(y2, curve.Params().P) + if y2.Cmp(x3) != 0 { + return nil, fmt.Errorf("invalid square root") + } + + // Verify that y-coord has expected parity. if ybit != isOdd(y) { return nil, fmt.Errorf("ybit doesn't match oddness") } + return y, nil }