From 5d0e3e0acc9094e1844c23fe346ab84c96bc9c8b Mon Sep 17 00:00:00 2001 From: AMIRUL IAN Date: Fri, 27 Nov 2026 22:03:33 +0800 Subject: [PATCH] Reject non-canonical Edwards point encodings in _from_edwards --- src/ecdsa/ellipticcurve.py | 7 +++++++ src/ecdsa/test_eddsa.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/ecdsa/ellipticcurve.py b/src/ecdsa/ellipticcurve.py index f601f263..e0a51a88 100644 --- a/src/ecdsa/ellipticcurve.py +++ b/src/ecdsa/ellipticcurve.py @@ -319,6 +319,8 @@ def _from_edwards(cls, curve, data): data[-1] &= 0x80 - 1 y = bytes_to_int(data, "little") + if y >= p: + raise MalformedPointError("Point y coordinate is larger than p.") if GMPY: y = mpz(y) @@ -335,6 +337,11 @@ def _from_edwards(cls, curve, data): "Encoding does not correspond to a point on curve", e ) + if x == 0 and x_0: + raise MalformedPointError( + "Invalid encoding of x=0 with sign bit 1" + ) + if x % 2 != x_0: x = -x % p diff --git a/src/ecdsa/test_eddsa.py b/src/ecdsa/test_eddsa.py index 6821b3bc..43f0ecc1 100644 --- a/src/ecdsa/test_eddsa.py +++ b/src/ecdsa/test_eddsa.py @@ -505,6 +505,37 @@ def test_ed448_invalid(self): with self.assertRaises(MalformedPointError): PointEdwards.from_bytes(curve_ed448, exp_bytes) + def test_ed25519_non_canonical_y(self): + # y = p + 1 = 2^255 - 18 (valid mod p since y ≡ 1, x = 0, but y >= p) + exp_bytes = ( + b"\xee\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + b"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x7f" + ) + with self.assertRaises(MalformedPointError): + PointEdwards.from_bytes(curve_ed25519, exp_bytes) + + def test_ed448_non_canonical_y(self): + # y = p + 1 on Ed448 (non-zero low bits in 57th byte) + exp_bytes = ( + b"\x00" * 28 + + b"\xff" * 27 + + b"\xfe\x01" + ) + with self.assertRaises(MalformedPointError): + PointEdwards.from_bytes(curve_ed448, exp_bytes) + + def test_ed25519_negative_zero_x(self): + # (x=0, y=1) encoded with sign bit x_0 = 1 (RFC 8032 Section 5.1.3) + exp_bytes = b"\x01" + b"\x00" * 30 + b"\x80" + with self.assertRaises(MalformedPointError): + PointEdwards.from_bytes(curve_ed25519, exp_bytes) + + def test_ed448_negative_zero_x(self): + # (x=0, y=1) encoded with sign bit x_0 = 1 (RFC 8032 Section 5.2.3) + exp_bytes = b"\x01" + b"\x00" * 55 + b"\x80" + with self.assertRaises(MalformedPointError): + PointEdwards.from_bytes(curve_ed448, exp_bytes) + def test_ed448_encode(): g = generator_ed448 @@ -683,6 +714,13 @@ def test_invalid_r_value(self): with self.assertRaises(ValueError): key.verify(b"", sig_invalid) + def test_non_canonical_r_in_signature(self): + # Identity public key A = (0, 1); R = (0, 1) with sign bit x_0 = 1 + key = PublicKey(generator_ed25519, b"\x01" + b"\x00" * 31) + sig_neg_zero_r = (b"\x01" + b"\x00" * 30 + b"\x80") + (b"\x00" * 32) + with self.assertRaises(MalformedPointError): + key.verify(b"hello", sig_neg_zero_r) + HYP_SETTINGS = dict() if "--fast" in sys.argv: # pragma: no cover