-
Notifications
You must be signed in to change notification settings - Fork 96
/
group.py
282 lines (209 loc) · 7.66 KB
/
group.py
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
"""Basic modular math module.
Support for basic modular math in ElectionGuard. This code's primary purpose is to be "correct",
in the sense that performance may be less than hand-optimized C code, and no guarantees are
made about timing or other side-channels.
"""
from abc import ABC
from typing import Final, Optional, Union
from secrets import randbelow
from sys import maxsize
# pylint: disable=no-name-in-module
from gmpy2 import mpz, powmod, invert
from .big_integer import BigInteger
from .constants import get_large_prime, get_small_prime, get_generator
class BaseElement(BigInteger, ABC):
"""An element limited by mod T within [0, T) where T is determined by an upper_bound function."""
def __new__(cls, data: Union[int, str], check_within_bounds: bool = True): # type: ignore
"""Instantiate element mod T where element is an int or its hex representation."""
element = super(BaseElement, cls).__new__(cls, data)
if check_within_bounds:
if not 0 <= element.value < cls.get_upper_bound():
raise OverflowError
return element
@classmethod
def get_upper_bound(cls) -> int:
"""Get the upper bound for the element."""
return maxsize
def is_in_bounds(self) -> bool:
"""
Validate that the element is actually within the bounds of [0,Q).
Returns true if all is good, false if something's wrong.
"""
return 0 <= self.value < self.get_upper_bound()
def is_in_bounds_no_zero(self) -> bool:
"""
Validate that the element is actually within the bounds of [1,Q).
Returns true if all is good, false if something's wrong.
"""
return 1 <= self.value < self.get_upper_bound()
class ElementModQ(BaseElement):
"""An element of the smaller `mod q` space, i.e., in [0, Q), where Q is a 256-bit prime."""
@classmethod
def get_upper_bound(cls) -> int:
"""Get the upper bound for the element."""
return get_small_prime()
class ElementModP(BaseElement):
"""An element of the larger `mod p` space, i.e., in [0, P), where P is a 4096-bit prime."""
@classmethod
def get_upper_bound(cls) -> int:
"""Get the upper bound for the element."""
return get_large_prime()
def is_valid_residue(self) -> bool:
"""Validate that this element is in Z^r_p."""
residue = pow_p(self, get_small_prime()) == ONE_MOD_P
return self.is_in_bounds() and residue
# Common constants
ZERO_MOD_Q: Final[ElementModQ] = ElementModQ(0)
ONE_MOD_Q: Final[ElementModQ] = ElementModQ(1)
TWO_MOD_Q: Final[ElementModQ] = ElementModQ(2)
ZERO_MOD_P: Final[ElementModP] = ElementModP(0)
ONE_MOD_P: Final[ElementModP] = ElementModP(1)
TWO_MOD_P: Final[ElementModP] = ElementModP(2)
ElementModPOrQ = Union[ElementModP, ElementModQ]
ElementModPOrQorInt = Union[ElementModP, ElementModQ, int]
ElementModQorInt = Union[ElementModQ, int]
ElementModPorInt = Union[ElementModP, int]
def _get_mpz(input: Union[BaseElement, int]) -> mpz:
"""Get BaseElement or integer as mpz."""
if isinstance(input, BaseElement):
return input.value
return mpz(input)
def hex_to_q(input: str) -> Optional[ElementModQ]:
"""
Given a hex string representing bytes, returns an ElementModQ.
Returns `None` if the number is out of the allowed [0,Q) range.
"""
try:
return ElementModQ(input)
except OverflowError:
return None
def int_to_q(input: int) -> Optional[ElementModQ]:
"""
Given a Python integer, returns an ElementModQ.
Returns `None` if the number is out of the allowed [0,Q) range.
"""
try:
return ElementModQ(input)
except OverflowError:
return None
def hex_to_p(input: str) -> Optional[ElementModP]:
"""
Given a hex string representing bytes, returns an ElementModP.
Returns `None` if the number is out of the allowed [0,Q) range.
"""
try:
return ElementModP(input)
except OverflowError:
return None
def int_to_p(input: int) -> Optional[ElementModP]:
"""
Given a Python integer, returns an ElementModP.
Returns `None` if the number is out of the allowed [0,P) range.
"""
try:
return ElementModP(input)
except OverflowError:
return None
def add_q(*elems: ElementModQorInt) -> ElementModQ:
"""Add together one or more elements in Q, returns the sum mod Q."""
sum = _get_mpz(0)
for e in elems:
e = _get_mpz(e)
sum = (sum + e) % get_small_prime()
return ElementModQ(sum)
def a_minus_b_q(a: ElementModQorInt, b: ElementModQorInt) -> ElementModQ:
"""Compute (a-b) mod q."""
a = _get_mpz(a)
b = _get_mpz(b)
return ElementModQ((a - b) % get_small_prime())
def div_p(a: ElementModPOrQorInt, b: ElementModPOrQorInt) -> ElementModP:
"""Compute a/b mod p."""
b = _get_mpz(b)
inverse = invert(b, _get_mpz(get_large_prime()))
return mult_p(a, inverse)
def div_q(a: ElementModPOrQorInt, b: ElementModPOrQorInt) -> ElementModQ:
"""Compute a/b mod q."""
b = _get_mpz(b)
inverse = invert(b, _get_mpz(get_small_prime()))
return mult_q(a, inverse)
def negate_q(a: ElementModQorInt) -> ElementModQ:
"""Compute (Q - a) mod q."""
a = _get_mpz(a)
return ElementModQ(get_small_prime() - a)
def a_plus_bc_q(
a: ElementModQorInt, b: ElementModQorInt, c: ElementModQorInt
) -> ElementModQ:
"""Compute (a + b * c) mod q."""
a = _get_mpz(a)
b = _get_mpz(b)
c = _get_mpz(c)
return ElementModQ((a + b * c) % get_small_prime())
def mult_inv_p(e: ElementModPOrQorInt) -> ElementModP:
"""
Compute the multiplicative inverse mod p.
:param e: An element in [1, P).
"""
e = _get_mpz(e)
assert e != 0, "No multiplicative inverse for zero"
return ElementModP(powmod(e, -1, get_large_prime()))
def pow_p(b: ElementModPOrQorInt, e: ElementModPOrQorInt) -> ElementModP:
"""
Compute b^e mod p.
:param b: An element in [0,P).
:param e: An element in [0,P).
"""
b = _get_mpz(b)
e = _get_mpz(e)
return ElementModP(powmod(b, e, get_large_prime()))
def pow_q(b: ElementModQorInt, e: ElementModQorInt) -> ElementModQ:
"""
Compute b^e mod q.
:param b: An element in [0,Q).
:param e: An element in [0,Q).
"""
b = _get_mpz(b)
e = _get_mpz(e)
return ElementModQ(powmod(b, e, get_small_prime()))
def mult_p(*elems: ElementModPOrQorInt) -> ElementModP:
"""
Compute the product, mod p, of all elements.
:param elems: Zero or more elements in [0,P).
"""
product = _get_mpz(1)
for x in elems:
x = _get_mpz(x)
product = (product * x) % get_large_prime()
return ElementModP(product)
def mult_q(*elems: ElementModPOrQorInt) -> ElementModQ:
"""
Compute the product, mod q, of all elements.
:param elems: Zero or more elements in [0,Q).
"""
product = _get_mpz(1)
for x in elems:
x = _get_mpz(x)
product = (product * x) % get_small_prime()
return ElementModQ(product)
def g_pow_p(e: ElementModPOrQorInt) -> ElementModP:
"""
Compute g^e mod p.
:param e: An element in [0,P).
"""
return pow_p(get_generator(), e)
def rand_q() -> ElementModQ:
"""
Generate random number between 0 and Q.
:return: Random value between 0 and Q
"""
return ElementModQ(randbelow(get_small_prime()))
def rand_range_q(start: ElementModQorInt) -> ElementModQ:
"""
Generate random number between start and Q.
:param start: Starting value of range
:return: Random value between start and Q
"""
start = _get_mpz(start)
random = 0
while random < start:
random = randbelow(get_small_prime())
return ElementModQ(random)