aboutsummaryrefslogtreecommitdiff
path: root/pyecsca/ec/mult/binary.py
blob: f0cb5ac963aab3d37d39f524d329ba500ea630e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""Provides binary scalar multipliers (LTR and RTL), that process the scalar as-is, bit-by-bit."""
from abc import ABC
from copy import copy
from typing import Optional

from public import public

from pyecsca.ec.mult.base import (
    ScalarMultiplier,
    ProcessingDirection,
    AccumulationOrder,
    ScalarMultiplicationAction,
    AccumulatorMultiplier,
)
from pyecsca.ec.formula import AdditionFormula, DoublingFormula, ScalingFormula
from pyecsca.ec.point import Point


@public
class DoubleAndAddMultiplier(AccumulatorMultiplier, ScalarMultiplier, ABC):
    """
    Classic double and add scalar multiplication algorithm.

    .. note::
        This is an ABC, you should use the `LTRMultiplier` and `RTLMultiplier` classes.

    :param short_circuit: Whether the use of formulas will be guarded by short-circuit on inputs
                          of the point at infinity.
    :param always: Whether the double and add always method is used.
    :param direction: Whether it is LTR or RTL.
    :param accumulation_order: The order of accumulation of points.
    :param complete: Whether it starts processing at full order-bit-length.
    """

    requires = {AdditionFormula, DoublingFormula}
    optionals = {ScalingFormula}
    always: bool
    """Whether the double and add always method is used."""
    direction: ProcessingDirection
    """Whether it is LTR or RTL."""
    complete: bool
    """Whether it starts processing at full order-bit-length."""

    def __init__(
        self,
        add: AdditionFormula,
        dbl: DoublingFormula,
        scl: Optional[ScalingFormula] = None,
        always: bool = False,
        direction: ProcessingDirection = ProcessingDirection.LTR,
        accumulation_order: AccumulationOrder = AccumulationOrder.PeqPR,
        complete: bool = True,
        short_circuit: bool = True,
    ):
        super().__init__(
            short_circuit=short_circuit,
            accumulation_order=accumulation_order,
            add=add,
            dbl=dbl,
            scl=scl,
        )
        self.always = always
        self.direction = direction
        self.complete = complete

    def __hash__(self):
        return hash(
            (
                DoubleAndAddMultiplier,
                super().__hash__(),
                self.direction,
                self.accumulation_order,
                self.always,
                self.complete,
            )
        )

    def __eq__(self, other):
        if not isinstance(other, DoubleAndAddMultiplier):
            return False
        return (
            self.formulas == other.formulas
            and self.short_circuit == other.short_circuit
            and self.direction == other.direction
            and self.accumulation_order == other.accumulation_order
            and self.always == other.always
            and self.complete == other.complete
        )

    def __repr__(self):
        return f"{self.__class__.__name__}({', '.join(map(str, self.formulas.values()))}, short_circuit={self.short_circuit}, direction={self.direction.name}, accumulation_order={self.accumulation_order.name}, always={self.always}, complete={self.complete})"

    def _ltr(self, scalar: int) -> Point:
        if self.complete:
            q = self._point
            r = copy(self._params.curve.neutral)
            top = self._bits - 1
        else:
            q = copy(self._point)
            r = copy(self._point)
            top = scalar.bit_length() - 2
        for i in range(top, -1, -1):
            r = self._dbl(r)
            if scalar & (1 << i) != 0:
                r = self._accumulate(r, q)
            elif self.always:
                # dummy add
                self._accumulate(r, q)
        return r

    def _rtl(self, scalar: int) -> Point:
        q = self._point
        r = copy(self._params.curve.neutral)
        if self.complete:
            top = self._bits
        else:
            top = scalar.bit_length()
        for _ in range(top):
            if scalar & 1 != 0:
                r = self._accumulate(r, q)
            elif self.always:
                # dummy add
                self._accumulate(r, q)
            # TODO: This double is unnecessary in the last iteration.
            q = self._dbl(q)
            scalar >>= 1
        return r

    def multiply(self, scalar: int) -> Point:
        if not self._initialized:
            raise ValueError("ScalarMultiplier not initialized.")
        with ScalarMultiplicationAction(self._point, self._params, scalar) as action:
            if scalar == 0:
                return action.exit(copy(self._params.curve.neutral))
            if self.direction is ProcessingDirection.LTR:
                r = self._ltr(scalar)
            elif self.direction is ProcessingDirection.RTL:
                r = self._rtl(scalar)
            if "scl" in self.formulas:
                r = self._scl(r)
            return action.exit(r)


@public
class LTRMultiplier(DoubleAndAddMultiplier):
    """
    Classic double and add scalar multiplication algorithm, that scans the scalar left-to-right (msb to lsb).

    :param short_circuit: Whether the use of formulas will be guarded by short-circuit on inputs
                          of the point at infinity.
    :param always: Whether the double and add always method is used.
    :param accumulation_order: The order of accumulation of points.
    :param complete: Whether it starts processing at full order-bit-length.
    """

    def __init__(
        self,
        add: AdditionFormula,
        dbl: DoublingFormula,
        scl: Optional[ScalingFormula] = None,
        always: bool = False,
        accumulation_order: AccumulationOrder = AccumulationOrder.PeqPR,
        complete: bool = True,
        short_circuit: bool = True,
    ):
        super().__init__(
            short_circuit=short_circuit,
            direction=ProcessingDirection.LTR,
            accumulation_order=accumulation_order,
            always=always,
            complete=complete,
            add=add,
            dbl=dbl,
            scl=scl,
        )


@public
class RTLMultiplier(DoubleAndAddMultiplier):
    """
    Classic double and add scalar multiplication algorithm, that scans the scalar right-to-left (lsb to msb).

    :param short_circuit: Whether the use of formulas will be guarded by short-circuit on inputs
                          of the point at infinity.
    :param always: Whether the double and add always method is used.
    :param accumulation_order: The order of accumulation of points.
    :param complete: Whether it starts processing at full order-bit-length.
    """

    def __init__(
        self,
        add: AdditionFormula,
        dbl: DoublingFormula,
        scl: Optional[ScalingFormula] = None,
        always: bool = False,
        accumulation_order: AccumulationOrder = AccumulationOrder.PeqPR,
        complete: bool = True,
        short_circuit: bool = True,
    ):
        super().__init__(
            short_circuit=short_circuit,
            direction=ProcessingDirection.RTL,
            accumulation_order=accumulation_order,
            always=always,
            add=add,
            dbl=dbl,
            scl=scl,
            complete=complete,
        )


@public
class CoronMultiplier(ScalarMultiplier):
    """
    Coron's double and add resistant against SPA.

    From [CO2002]_.

    :param short_circuit: Whether the use of formulas will be guarded by short-circuit on inputs
                          of the point at infinity.
    """

    requires = {AdditionFormula, DoublingFormula}
    optionals = {ScalingFormula}

    def __init__(
        self,
        add: AdditionFormula,
        dbl: DoublingFormula,
        scl: Optional[ScalingFormula] = None,
        short_circuit: bool = True,
    ):
        super().__init__(short_circuit=short_circuit, add=add, dbl=dbl, scl=scl)

    def __hash__(self):
        return hash((CoronMultiplier, super().__hash__()))

    def __eq__(self, other):
        if not isinstance(other, CoronMultiplier):
            return False
        return (
            self.formulas == other.formulas
            and self.short_circuit == other.short_circuit
        )

    def multiply(self, scalar: int) -> Point:
        if not self._initialized:
            raise ValueError("ScalarMultiplier not initialized.")
        with ScalarMultiplicationAction(self._point, self._params, scalar) as action:
            if scalar == 0:
                return action.exit(copy(self._params.curve.neutral))
            q = self._point
            p0 = copy(q)
            for i in range(scalar.bit_length() - 2, -1, -1):
                p0 = self._dbl(p0)
                p1 = self._add(p0, q)
                if scalar & (1 << i) != 0:
                    p0 = p1
            if "scl" in self.formulas:
                p0 = self._scl(p0)
            return action.exit(p0)