Debian Codegraph @

lib/Crypto/Math/_IntegerBase.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2018, Helder Eijs <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 import abc
32
33 from Crypto.Util.py3compat import iter_range, bord, bchr, ABC
34
35 from Crypto import Random
36
37
38 class IntegerBase(ABC):
39
40 # Conversions
41 @abc.abstractmethod
42 def __int__(self):
43 pass
44
45 @abc.abstractmethod
46 def __str__(self):
47 pass
48
49 @abc.abstractmethod
50 def __repr__(self):
51 pass
52
53 @abc.abstractmethod
54 def to_bytes(self, block_size=0, byteorder='big'):
55 pass
56
57 @staticmethod
58 @abc.abstractmethod
59 def from_bytes(byte_string, byteorder='big'):
60 pass
61
62 # Relations
63 @abc.abstractmethod
64 def __eq__(self, term):
65 pass
66
67 @abc.abstractmethod
68 def __ne__(self, term):
69 pass
70
71 @abc.abstractmethod
72 def __lt__(self, term):
73 pass
74
75 @abc.abstractmethod
76 def __le__(self, term):
77 pass
78
79 @abc.abstractmethod
80 def __gt__(self, term):
81 pass
82
83 @abc.abstractmethod
84 def __ge__(self, term):
85 pass
86
87 @abc.abstractmethod
88 def __nonzero__(self):
89 pass
90 __bool__ = __nonzero__
91
92 @abc.abstractmethod
93 def is_negative(self):
94 pass
95
96 # Arithmetic operations
97 @abc.abstractmethod
98 def __add__(self, term):
99 pass
100
101 @abc.abstractmethod
102 def __sub__(self, term):
103 pass
104
105 @abc.abstractmethod
106 def __mul__(self, factor):
107 pass
108
109 @abc.abstractmethod
110 def __floordiv__(self, divisor):
111 pass
112
113 @abc.abstractmethod
114 def __mod__(self, divisor):
115 pass
116
117 @abc.abstractmethod
118 def inplace_pow(self, exponent, modulus=None):
119 pass
120
121 @abc.abstractmethod
122 def __pow__(self, exponent, modulus=None):
123 pass
124
125 @abc.abstractmethod
126 def __abs__(self):
127 pass
128
129 @abc.abstractmethod
130 def sqrt(self, modulus=None):
131 pass
132
133 @abc.abstractmethod
134 def __iadd__(self, term):
135 pass
136
137 @abc.abstractmethod
138 def __isub__(self, term):
139 pass
140
141 @abc.abstractmethod
142 def __imul__(self, term):
143 pass
144
145 @abc.abstractmethod
146 def __imod__(self, term):
147 pass
148
149 # Boolean/bit operations
150 @abc.abstractmethod
151 def __and__(self, term):
152 pass
153
154 @abc.abstractmethod
155 def __or__(self, term):
156 pass
157
158 @abc.abstractmethod
159 def __rshift__(self, pos):
160 pass
161
162 @abc.abstractmethod
163 def __irshift__(self, pos):
164 pass
165
166 @abc.abstractmethod
167 def __lshift__(self, pos):
168 pass
169
170 @abc.abstractmethod
171 def __ilshift__(self, pos):
172 pass
173
174 @abc.abstractmethod
175 def get_bit(self, n):
176 pass
177
178 # Extra
179 @abc.abstractmethod
180 def is_odd(self):
181 pass
182
183 @abc.abstractmethod
184 def is_even(self):
185 pass
186
187 @abc.abstractmethod
188 def size_in_bits(self):
189 pass
190
191 @abc.abstractmethod
192 def size_in_bytes(self):
193 pass
194
195 @abc.abstractmethod
196 def is_perfect_square(self):
197 pass
198
199 @abc.abstractmethod
200 def fail_if_divisible_by(self, small_prime):
201 pass
202
203 @abc.abstractmethod
204 def multiply_accumulate(self, a, b):
205 pass
206
207 @abc.abstractmethod
208 def set(self, source):
209 pass
210
211 @abc.abstractmethod
212 def inplace_inverse(self, modulus):
213 pass
214
215 @abc.abstractmethod
216 def inverse(self, modulus):
217 pass
218
219 @abc.abstractmethod
220 def gcd(self, term):
221 pass
222
223 @abc.abstractmethod
224 def lcm(self, term):
225 pass
226
227 @staticmethod
228 @abc.abstractmethod
229 def jacobi_symbol(a, n):
230 pass
231
232 @staticmethod
233 def _tonelli_shanks(n, p):
234 """Tonelli-shanks algorithm for computing the square root
235 of n modulo a prime p.
236
237 n must be in the range [0..p-1].
238 p must be at least even.
239
240 The return value r is the square root of modulo p. If non-zero,
241 another solution will also exist (p-r).
242
243 Note we cannot assume that p is really a prime: if it's not,
244 we can either raise an exception or return the correct value.
245 """
246
247 # See https://rosettacode.org/wiki/Tonelli-Shanks_algorithm
248
249 if n in (0, 1):
250 return n
251
252 if p % 4 == 3:
253 root = pow(n, (p + 1) // 4, p)
254 if pow(root, 2, p) != n:
255 raise ValueError("Cannot compute square root")
256 return root
257
258 s = 1
259 q = (p - 1) // 2
260 while not (q & 1):
261 s += 1
262 q >>= 1
263
264 z = n.__class__(2)
265 while True:
266 euler = pow(z, (p - 1) // 2, p)
267 if euler == 1:
268 z += 1
269 continue
270 if euler == p - 1:
271 break
272 # Most probably p is not a prime
273 raise ValueError("Cannot compute square root")
274
275 m = s
276 c = pow(z, q, p)
277 t = pow(n, q, p)
278 r = pow(n, (q + 1) // 2, p)
279
280 while t != 1:
281 for i in iter_range(0, m):
282 if pow(t, 2**i, p) == 1:
283 break
284 if i == m:
285 raise ValueError("Cannot compute square root of %d mod %d" % (n, p))
286 b = pow(c, 2**(m - i - 1), p)
287 m = i
288 c = b**2 % p
289 t = (t * b**2) % p
290 r = (r * b) % p
291
292 if pow(r, 2, p) != n:
293 raise ValueError("Cannot compute square root")
294
295 return r
296
297 @classmethod
298 def random(cls, **kwargs):
299 """Generate a random natural integer of a certain size.
300
301 :Keywords:
302 exact_bits : positive integer
303 The length in bits of the resulting random Integer number.
304 The number is guaranteed to fulfil the relation:
305
306 2^bits > result >= 2^(bits - 1)
307
308 max_bits : positive integer
309 The maximum length in bits of the resulting random Integer number.
310 The number is guaranteed to fulfil the relation:
311
312 2^bits > result >=0
313
314 randfunc : callable
315 A function that returns a random byte string. The length of the
316 byte string is passed as parameter. Optional.
317 If not provided (or ``None``), randomness is read from the system RNG.
318
319 :Return: a Integer object
320 """
321
322 exact_bits = kwargs.pop("exact_bits", None)
323 max_bits = kwargs.pop("max_bits", None)
324 randfunc = kwargs.pop("randfunc", None)
325
326 if randfunc is None:
327 randfunc = Random.new().read
328
329 if exact_bits is None and max_bits is None:
330 raise ValueError("Either 'exact_bits' or 'max_bits' must be specified")
331
332 if exact_bits is not None and max_bits is not None:
333 raise ValueError("'exact_bits' and 'max_bits' are mutually exclusive")
334
335 bits = exact_bits or max_bits
336 bytes_needed = ((bits - 1) // 8) + 1
337 significant_bits_msb = 8 - (bytes_needed * 8 - bits)
338 msb = bord(randfunc(1)[0])
339 if exact_bits is not None:
340 msb |= 1 << (significant_bits_msb - 1)
341 msb &= (1 << significant_bits_msb) - 1
342
343 return cls.from_bytes(bchr(msb) + randfunc(bytes_needed - 1))
344
345 @classmethod
346 def random_range(cls, **kwargs):
347 """Generate a random integer within a given internal.
348
349 :Keywords:
350 min_inclusive : integer
351 The lower end of the interval (inclusive).
352 max_inclusive : integer
353 The higher end of the interval (inclusive).
354 max_exclusive : integer
355 The higher end of the interval (exclusive).
356 randfunc : callable
357 A function that returns a random byte string. The length of the
358 byte string is passed as parameter. Optional.
359 If not provided (or ``None``), randomness is read from the system RNG.
360 :Returns:
361 An Integer randomly taken in the given interval.
362 """
363
364 min_inclusive = kwargs.pop("min_inclusive", None)
365 max_inclusive = kwargs.pop("max_inclusive", None)
366 max_exclusive = kwargs.pop("max_exclusive", None)
367 randfunc = kwargs.pop("randfunc", None)
368
369 if kwargs:
370 raise ValueError("Unknown keywords: " + str(kwargs.keys))
371 if None not in (max_inclusive, max_exclusive):
372 raise ValueError("max_inclusive and max_exclusive cannot be both"
373 " specified")
374 if max_exclusive is not None:
375 max_inclusive = max_exclusive - 1
376 if None in (min_inclusive, max_inclusive):
377 raise ValueError("Missing keyword to identify the interval")
378
379 if randfunc is None:
380 randfunc = Random.new().read
381
382 norm_maximum = max_inclusive - min_inclusive
383 bits_needed = cls(norm_maximum).size_in_bits()
384
385 norm_candidate = -1
386 while not 0 <= norm_candidate <= norm_maximum:
387 norm_candidate = cls.random(
388 max_bits=bits_needed,
389 randfunc=randfunc
390 )
391 return norm_candidate + min_inclusive
392
393 @staticmethod
394 @abc.abstractmethod
395 def _mult_modulo_bytes(term1, term2, modulus):
396 """Multiply two integers, take the modulo, and encode as big endian.
397 This specialized method is used for RSA decryption.
398
399 Args:
400 term1 : integer
401 The first term of the multiplication, non-negative.
402 term2 : integer
403 The second term of the multiplication, non-negative.
404 modulus: integer
405 The modulus, a positive odd number.
406 :Returns:
407 A byte string, with the result of the modular multiplication
408 encoded in big endian mode.
409 It is as long as the modulus would be, with zero padding
410 on the left if needed.
411 """
412 pass