Skip to content

Commit 8c5704e

Browse files
committed
use simple double and add algorithm in Point
So, X9.62 looks to be trying to protect against side-channels from double and add by doing a "addition-subtraction method" in section D.3.2. For some reason, that doesn't work for all parameters (see issue #373). Given that we don't have a need for side-channel resistance, and this is not a faster algorithm than double and add, just use double and add.
1 parent 6e6dbf1 commit 8c5704e

2 files changed

Lines changed: 22 additions & 27 deletions

File tree

src/ecdsa/ellipticcurve.py

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,13 +1207,6 @@ def __add__(self, other):
12071207
def __mul__(self, other):
12081208
"""Multiply a point by an integer."""
12091209

1210-
def leftmost_bit(x):
1211-
assert x > 0
1212-
result = 1
1213-
while result <= x:
1214-
result = 2 * result
1215-
return result // 2
1216-
12171210
e = other
12181211
if e == 0 or (self.__order and e % self.__order == 0):
12191212
return INFINITY
@@ -1222,26 +1215,14 @@ def leftmost_bit(x):
12221215
if e < 0:
12231216
return (-self) * (-e)
12241217

1225-
# From X9.62 D.3.2:
1226-
1227-
e3 = 3 * e
1228-
negative_self = Point(
1229-
self.__curve,
1230-
self.__x,
1231-
(-self.__y) % self.__curve.p(),
1232-
self.__order,
1233-
)
1234-
i = leftmost_bit(e3) // 2
1235-
result = self
1236-
# print("Multiplying %s by %d (e3 = %d):" % (self, other, e3))
1237-
while i > 1:
1238-
result = result.double()
1239-
if (e3 & i) != 0 and (e & i) == 0:
1240-
result = result + self
1241-
if (e3 & i) == 0 and (e & i) != 0:
1242-
result = result + negative_self
1243-
# print(". . . i = %d, result = %s" % ( i, result ))
1244-
i = i // 2
1218+
i = e
1219+
temp = self
1220+
result = INFINITY
1221+
while i:
1222+
if i % 2 == 1:
1223+
result = result + temp
1224+
temp = temp.double()
1225+
i = i >> 1
12451226

12461227
return result
12471228

src/ecdsa/test_ellipticcurve.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,20 @@ def test_add_and_mult_equivalence(p, m, check):
7171
assert p * m == check
7272

7373

74+
# from https://github.com/tlsfuzzer/python-ecdsa/issues/373
75+
curve = CurveFp(p=31, a=2, b=3)
76+
point = Point(curve, 6, 18)
77+
78+
79+
@pytest.mark.parametrize(
80+
"p, m, check",
81+
[(point, n, exp) for n, exp in enumerate(add_n_times(point, 16))],
82+
ids=["p31 test with mult {0}".format(i) for i in range(17)],
83+
)
84+
def test_add_and_mult_equivalence_2(p, m, check):
85+
assert p * m == check
86+
87+
7488
class TestCurve(unittest.TestCase):
7589
@classmethod
7690
def setUpClass(cls):

0 commit comments

Comments
 (0)