Skip to content

Commit 47c6126

Browse files
committed
handle non-prime order curves more gracefully
when the order of the curve is not a prime, then point doubling can return INFINITY, this will cause some negative values not to be reduced modulo curve p; fix this
1 parent 35c33f2 commit 47c6126

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/ecdsa/ellipticcurve.py

+12-3
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,7 @@ def to_affine(self):
728728
return INFINITY
729729
self.scale()
730730
x, y, z = self.__coords
731+
assert z == 1
731732
return Point(self.__curve, x, y, self.__order)
732733

733734
@staticmethod
@@ -887,9 +888,9 @@ def __radd__(self, other):
887888
def _add(self, X1, Y1, Z1, X2, Y2, Z2, p):
888889
"""add two points, select fastest method."""
889890
if not Y1 or not Z1:
890-
return X2, Y2, Z2
891+
return X2 % p, Y2 % p, Z2 % p
891892
if not Y2 or not Z2:
892-
return X1, Y1, Z1
893+
return X1 % p, Y1 % p, Z1 % p
893894
if Z1 == Z2:
894895
if Z1 == 1:
895896
return self._add_with_z_1(X1, Y1, X2, Y2, p)
@@ -1220,7 +1221,12 @@ def leftmost_bit(x):
12201221
# From X9.62 D.3.2:
12211222

12221223
e3 = 3 * e
1223-
negative_self = Point(self.__curve, self.__x, -self.__y, self.__order)
1224+
negative_self = Point(
1225+
self.__curve,
1226+
self.__x,
1227+
(-self.__y) % self.__curve.p(),
1228+
self.__order,
1229+
)
12241230
i = leftmost_bit(e3) // 2
12251231
result = self
12261232
# print("Multiplying %s by %d (e3 = %d):" % (self, other, e3))
@@ -1264,6 +1270,9 @@ def double(self):
12641270
x3 = (l * l - 2 * self.__x) % p
12651271
y3 = (l * (self.__x - x3) - self.__y) % p
12661272

1273+
if y3 == 0:
1274+
return INFINITY
1275+
12671276
return Point(self.__curve, x3, y3)
12681277

12691278
def x(self):

0 commit comments

Comments
 (0)