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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
|
"""Provides several countermeasures against side-channel attacks."""
from abc import ABC, abstractmethod
from typing import Optional, Callable
from public import public
from pyecsca.ec.formula import AdditionFormula
from pyecsca.ec.mod import Mod, mod
from pyecsca.ec.mult import ScalarMultiplier, ScalarMultiplicationAction
from pyecsca.ec.params import DomainParameters
from pyecsca.ec.point import Point
@public
class ScalarMultiplierCountermeasure(ABC):
"""
A scalar multiplier-based countermeasure.
This class behaves like a scalar multiplier, in fact it wraps one
and provides some scalar-splitting countermeasure.
"""
mult: "ScalarMultiplier | ScalarMultiplierCountermeasure"
"""The underlying scalar multiplier (or another countermeasure)."""
params: Optional[DomainParameters]
"""The domain parameters, if any."""
point: Optional[Point]
"""The point to multiply, if any."""
bits: Optional[int]
"""The bit-length to use, if any."""
def __init__(
self,
mult: "ScalarMultiplier | ScalarMultiplierCountermeasure",
rng: Callable[[int], Mod] = Mod.random,
):
self.mult = mult
self.rng = rng
def init(self, params: DomainParameters, point: Point, bits: Optional[int] = None):
"""Initialize the countermeasure with the parameters and the point."""
self.params = params
self.point = point
if bits is None:
bits = params.full_order.bit_length()
self.bits = bits
@abstractmethod
def multiply(self, scalar: int) -> Point:
"""
Multiply the point with the scalar using the countermeasure.
.. note::
The countermeasure may compute multiple scalar multiplications internally.
Thus, it may call the init method of the scalar multiplier multiple times.
:param scalar: The scalar to multiply with.
:return: The result of the multiplication.
"""
raise NotImplementedError
@public
class GroupScalarRandomization(ScalarMultiplierCountermeasure):
r"""
Group scalar randomization countermeasure.
Samples a random multiple, multiplies the order with it and adds it to the scalar.
.. math::
:class: frame
&r \xleftarrow{\$} \{0, 1, \ldots, 2^{\text{rand_bits}}\} \\
&\textbf{return}\ [k + r n]G
"""
rand_bits: int
def __init__(
self,
mult: "ScalarMultiplier | ScalarMultiplierCountermeasure",
rng: Callable[[int], Mod] = Mod.random,
rand_bits: int = 32,
):
"""
:param mult: The multiplier to use.
:param rand_bits: How many random bits to sample.
"""
super().__init__(mult, rng)
self.rand_bits = rand_bits
def multiply(self, scalar: int) -> Point:
if self.params is None or self.point is None or self.bits is None:
raise ValueError("Not initialized.")
with ScalarMultiplicationAction(self.point, self.params, scalar) as action:
order = self.params.order
mask = int(self.rng(1 << self.rand_bits))
masked_scalar = scalar + mask * order
bits = max(self.bits, self.rand_bits + order.bit_length()) + 1
self.mult.init(
self.params,
self.point,
bits=bits,
)
return action.exit(self.mult.multiply(masked_scalar))
@public
class AdditiveSplitting(ScalarMultiplierCountermeasure):
r"""
Additive splitting countermeasure.
Splits the scalar into two parts additively, multiplies the point with them and adds the results.
.. math::
:class: frame
&r \xleftarrow{\$} \{0, 1, \ldots, n\} \\
&\textbf{return}\ [k - r]G + [r]G
"""
add: Optional[AdditionFormula]
def __init__(
self,
mult: "ScalarMultiplier | ScalarMultiplierCountermeasure",
rng: Callable[[int], Mod] = Mod.random,
add: Optional[AdditionFormula] = None,
):
"""
:param mult: The multiplier to use.
:param add: Addition formula to use, if None, the formula from the multiplier is used.
"""
super().__init__(mult, rng)
self.add = add
def _add(self, R: Point, S: Point) -> Point: # noqa
if self.add is None:
try:
return self.mult._add(R, S) # type: ignore
except AttributeError:
raise ValueError("No addition formula available.")
else:
return self.add(
self.params.curve.prime, R, S, **self.params.curve.parameters # type: ignore
)[0]
def multiply(self, scalar: int) -> Point:
if self.params is None or self.point is None or self.bits is None:
raise ValueError("Not initialized.")
with ScalarMultiplicationAction(self.point, self.params, scalar) as action:
order = self.params.order
r = self.rng(order)
s = scalar - r
bits = max(self.bits, order.bit_length())
self.mult.init(self.params, self.point, bits)
R = self.mult.multiply(int(r))
S = self.mult.multiply(int(s))
res = self._add(R, S)
return action.exit(res)
@public
class MultiplicativeSplitting(ScalarMultiplierCountermeasure):
r"""
Multiplicative splitting countermeasure.
Splits the scalar into two parts multiplicatively, multiplies the point with them and adds the results.
.. math::
:class: frame
&r \xleftarrow{\$} \{0, 1, \ldots, 2^{\text{rand_bits}}\} \\
&S = [r]G \\
&\textbf{return}\ [k r^{-1} \mod n]S
"""
rand_bits: int
def __init__(
self,
mult: "ScalarMultiplier | ScalarMultiplierCountermeasure",
rng: Callable[[int], Mod] = Mod.random,
rand_bits: int = 32,
):
"""
:param mult: The multiplier to use.
:param rand_bits: How many random bits to sample.
"""
super().__init__(mult, rng)
self.rand_bits = rand_bits
def multiply(self, scalar: int) -> Point:
if self.params is None or self.point is None or self.bits is None:
raise ValueError("Not initialized.")
with ScalarMultiplicationAction(self.point, self.params, scalar) as action:
r = self.rng(1 << self.rand_bits)
self.mult.init(self.params, self.point, self.rand_bits)
R = self.mult.multiply(int(r))
self.mult.init(
self.params, R, max(self.bits, self.params.order.bit_length())
)
kr_inv = scalar * mod(int(r), self.params.order).inverse()
return action.exit(self.mult.multiply(int(kr_inv)))
@public
class EuclideanSplitting(ScalarMultiplierCountermeasure):
r"""
Euclidean splitting countermeasure.
Picks a random value half the size of the curve, then splits the scalar
into the remainder and the quotient of the division by the random value.
.. math::
:class: frame
&r \xleftarrow{\$} \{0, 1, \ldots, 2^{\log_2{(n)}/2}\} \\
&S = [r]G \\
&k_1 = k \mod r \\
&k_2 = \lfloor \frac{k}{r} \rfloor \\
&\textbf{return}\ [k_1]G + [k_2]S
"""
add: Optional[AdditionFormula]
def __init__(
self,
mult: "ScalarMultiplier | ScalarMultiplierCountermeasure",
rng: Callable[[int], Mod] = Mod.random,
add: Optional[AdditionFormula] = None,
):
"""
:param mult: The multiplier to use.
:param add: Addition formula to use, if None, the formula from the multiplier is used.
"""
super().__init__(mult, rng)
self.add = add
def _add(self, R: Point, S: Point) -> Point: # noqa
if self.add is None:
try:
return self.mult._add(R, S) # type: ignore
except AttributeError:
raise ValueError("No addition formula available.")
else:
return self.add(
self.params.curve.prime, R, S, **self.params.curve.parameters # type: ignore
)[0]
def multiply(self, scalar: int) -> Point:
if self.params is None or self.point is None or self.bits is None:
raise ValueError("Not initialized.")
with ScalarMultiplicationAction(self.point, self.params, scalar) as action:
half_bits = self.bits // 2
r = self.rng(1 << half_bits)
self.mult.init(self.params, self.point, half_bits)
R = self.mult.multiply(int(r)) # r bounded by half_bits
k1 = scalar % int(r)
k2 = scalar // int(r)
T = self.mult.multiply(k1) # k1 bounded by half_bits
self.mult.init(self.params, R, self.bits)
S = self.mult.multiply(
k2
) # k2 (in worst case) bounded by bits, but in practice closer to half_bits
res = self._add(S, T)
return action.exit(res)
@public
class BrumleyTuveri(ScalarMultiplierCountermeasure):
r"""
A countermeasure that fixes the bit-length of the scalar by adding some multiple
of the order to it.
Originally proposed in [BT11]_.
.. math::
:class: frame
&\hat{k}= \begin{cases}
k + 2n \quad \text{if } \lceil \log_2(k+n) \rceil = \lceil \log_2 n \rceil\\
k + n \quad \text{otherwise}.
\end{cases}\\
&\textbf{return}\ [\hat{k}]G
"""
def multiply(self, scalar: int) -> Point:
if self.params is None or self.point is None or self.bits is None:
raise ValueError("Not initialized.")
with ScalarMultiplicationAction(self.point, self.params, scalar) as action:
n = self.params.order
self.mult.init(
self.params,
self.point,
bits=max(self.bits, n.bit_length()) + 1,
)
scalar += n
if scalar.bit_length() <= n.bit_length():
scalar += n
return action.exit(self.mult.multiply(scalar))
|