Skip to content

Commit 58eef88

Browse files
committed
faster double for scaled points
1 parent 48040d7 commit 58eef88

File tree

2 files changed

+35
-9
lines changed

2 files changed

+35
-9
lines changed

src/ecdsa/ellipticcurve.py

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -227,19 +227,28 @@ def from_affine(point, generator=False):
227227
# similarly, sometimes the `% p` is skipped if it makes the calculation
228228
# faster and the result of calculation is later reduced modulo `p`
229229

230-
def double(self):
231-
"""Add a point to itself."""
232-
if not self.__y:
230+
def _double_with_z_1(self, X1, Y1):
231+
"""Add a point to itself with z == 1."""
232+
# after:
233+
# http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-mdbl-2007-bl
234+
p, a = self.__curve.p(), self.__curve.a()
235+
XX, YY = X1 * X1 % p, Y1 * Y1 % p
236+
if not YY:
233237
return INFINITY
238+
YYYY = YY * YY % p
239+
S = 2 * ((X1 + YY)**2 - XX - YYYY) % p
240+
M = 3 * XX + a
241+
T = (M * M - 2 * S) % p
242+
# X3 = T
243+
Y3 = (M * (S - T) - 8 * YYYY) % p
244+
Z3 = 2 * Y1 % p
245+
return PointJacobi(self.__curve, T, Y3, Z3, self.__order)
234246

235-
p = self.__curve.p()
236-
a = self.__curve.a()
237-
238-
X1, Y1, Z1 = self.__x, self.__y, self.__z
239-
247+
def _double(self, X1, Y1, Z1):
248+
"""Add a point to itself, arbitrary z."""
240249
# after:
241250
# http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-2007-bl
242-
251+
p, a = self.__curve.p(), self.__curve.a()
243252
XX, YY = X1 * X1 % p, Y1 * Y1 % p
244253
if not YY:
245254
return INFINITY
@@ -254,6 +263,16 @@ def double(self):
254263

255264
return PointJacobi(self.__curve, T, Y3, Z3, self.__order)
256265

266+
def double(self):
267+
"""Add a point to itself."""
268+
if not self.__y:
269+
return INFINITY
270+
271+
X1, Y1, Z1 = self.__x, self.__y, self.__z
272+
if Z1 == 1:
273+
return self._double_with_z_1(X1, Y1)
274+
return self._double(X1, Y1, Z1)
275+
257276
def _add_with_z_1(self, X1, Y1, X2, Y2):
258277
"""add points when both Z1 and Z2 equal 1"""
259278
# after:

src/ecdsa/test_jacobi.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,13 @@ def test_double_with_zero_equivalent_point(self):
6969

7070
self.assertIs(pj, INFINITY)
7171

72+
def test_double_with_zero_equivalent_point_non_1_z(self):
73+
pj = PointJacobi(curve_256, 0, curve_256.p(), 2)
74+
75+
pj = pj.double()
76+
77+
self.assertIs(pj, INFINITY)
78+
7279
def test_compare_with_affine_point(self):
7380
pj = PointJacobi.from_affine(generator_256)
7481
pa = pj.to_affine()

0 commit comments

Comments
 (0)