keys: move IsOnCurve decoding check, add a test for it

This check only makes sense for 04-encoded points, because 02 and 03 derive Y
from X and they're on the curve by definition.
This commit is contained in:
Roman Khimov 2019-12-25 18:00:25 +03:00
parent 5ac8cae221
commit 6c471ecd98
2 changed files with 13 additions and 7 deletions

View file

@ -173,6 +173,8 @@ func (p *PublicKey) DecodeBinary(r *io.BinReader) {
return
}
p256 := elliptic.P256()
p256Params := p256.Params()
// Infinity
switch prefix {
case 0x00:
@ -202,17 +204,15 @@ func (p *PublicKey) DecodeBinary(r *io.BinReader) {
}
x = new(big.Int).SetBytes(xbytes)
y = new(big.Int).SetBytes(ybytes)
if !p256.IsOnCurve(x, y) {
r.Err = errors.New("encoded point is not on the P256 curve")
return
}
default:
r.Err = errors.Errorf("invalid prefix %d", prefix)
return
}
c := elliptic.P256()
cp := c.Params()
if !c.IsOnCurve(x, y) {
r.Err = errors.New("enccoded point is not on the P256 curve")
return
}
if x.Cmp(cp.P) >= 0 || y.Cmp(cp.P) >= 0 {
if x.Cmp(p256Params.P) >= 0 || y.Cmp(p256Params.P) >= 0 {
r.Err = errors.New("enccoded point is not correct (X or Y is bigger than P")
return
}

View file

@ -69,6 +69,12 @@ func TestDecodeFromStringBadCompressed(t *testing.T) {
require.Error(t, err)
}
func TestDecodeFromStringNotOnCurve(t *testing.T) {
str := "04ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
_, err := NewPublicKeyFromString(str)
require.Error(t, err)
}
func TestPubkeyToAddress(t *testing.T) {
pubKey, err := NewPublicKeyFromString("031ee4e73a17d8f76dc02532e2620bcb12425b33c0c9f9694cc2caa8226b68cad4")
require.NoError(t, err)