Debian Codegraph @

lib/Crypto/Math/_IntegerNative.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2014, Legrandin <[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 from ._IntegerBase import IntegerBase
32
33 from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse, GCD
34
35
36 class IntegerNative(IntegerBase):
37 """A class to model a natural integer (including zero)"""
38
39 def __init__(self, value):
40 if isinstance(value, float):
41 raise ValueError("A floating point type is not a natural number")
42 try:
43 self._value = value._value
44 except AttributeError:
45 self._value = value
46
47 # Conversions
48 def __int__(self):
49 return self._value
50
51 def __str__(self):
52 return str(int(self))
53
54 def __repr__(self):
55 return "Integer(%s)" % str(self)
56
57 # Only Python 2.x
58 def __hex__(self):
59 return hex(self._value)
60
61 # Only Python 3.x
62 def __index__(self):
63 return int(self._value)
64
65 def to_bytes(self, block_size=0, byteorder='big'):
66 if self._value < 0:
67 raise ValueError("Conversion only valid for non-negative numbers")
68 result = long_to_bytes(self._value, block_size)
69 if len(result) > block_size > 0:
70 raise ValueError("Value too large to encode")
71 if byteorder == 'big':
72 pass
73 elif byteorder == 'little':
74 result = bytearray(result)
75 result.reverse()
76 result = bytes(result)
77 else:
78 raise ValueError("Incorrect byteorder")
79 return result
80
81 @classmethod
82 def from_bytes(cls, byte_string, byteorder='big'):
83 if byteorder == 'big':
84 pass
85 elif byteorder == 'little':
86 byte_string = bytearray(byte_string)
87 byte_string.reverse()
88 else:
89 raise ValueError("Incorrect byteorder")
90 return cls(bytes_to_long(byte_string))
91
92 # Relations
93 def __eq__(self, term):
94 if term is None:
95 return False
96 return self._value == int(term)
97
98 def __ne__(self, term):
99 return not self.__eq__(term)
100
101 def __lt__(self, term):
102 return self._value < int(term)
103
104 def __le__(self, term):
105 return self.__lt__(term) or self.__eq__(term)
106
107 def __gt__(self, term):
108 return not self.__le__(term)
109
110 def __ge__(self, term):
111 return not self.__lt__(term)
112
113 def __nonzero__(self):
114 return self._value != 0
115 __bool__ = __nonzero__
116
117 def is_negative(self):
118 return self._value < 0
119
120 # Arithmetic operations
121 def __add__(self, term):
122 try:
123 return self.__class__(self._value + int(term))
124 except (ValueError, AttributeError, TypeError):
125 return NotImplemented
126
127 def __sub__(self, term):
128 try:
129 return self.__class__(self._value - int(term))
130 except (ValueError, AttributeError, TypeError):
131 return NotImplemented
132
133 def __mul__(self, factor):
134 try:
135 return self.__class__(self._value * int(factor))
136 except (ValueError, AttributeError, TypeError):
137 return NotImplemented
138
139 def __floordiv__(self, divisor):
140 return self.__class__(self._value // int(divisor))
141
142 def __mod__(self, divisor):
143 divisor_value = int(divisor)
144 if divisor_value < 0:
145 raise ValueError("Modulus must be positive")
146 return self.__class__(self._value % divisor_value)
147
148 def inplace_pow(self, exponent, modulus=None):
149 exp_value = int(exponent)
150 if exp_value < 0:
151 raise ValueError("Exponent must not be negative")
152
153 if modulus is not None:
154 mod_value = int(modulus)
155 if mod_value < 0:
156 raise ValueError("Modulus must be positive")
157 if mod_value == 0:
158 raise ZeroDivisionError("Modulus cannot be zero")
159 else:
160 mod_value = None
161 self._value = pow(self._value, exp_value, mod_value)
162 return self
163
164 def __pow__(self, exponent, modulus=None):
165 result = self.__class__(self)
166 return result.inplace_pow(exponent, modulus)
167
168 def __abs__(self):
169 return abs(self._value)
170
171 def sqrt(self, modulus=None):
172
173 value = self._value
174 if modulus is None:
175 if value < 0:
176 raise ValueError("Square root of negative value")
177 # http://stackoverflow.com/questions/15390807/integer-square-root-in-python
178
179 x = value
180 y = (x + 1) // 2
181 while y < x:
182 x = y
183 y = (x + value // x) // 2
184 result = x
185 else:
186 if modulus <= 0:
187 raise ValueError("Modulus must be positive")
188 result = self._tonelli_shanks(self % modulus, modulus)
189
190 return self.__class__(result)
191
192 def __iadd__(self, term):
193 self._value += int(term)
194 return self
195
196 def __isub__(self, term):
197 self._value -= int(term)
198 return self
199
200 def __imul__(self, term):
201 self._value *= int(term)
202 return self
203
204 def __imod__(self, term):
205 modulus = int(term)
206 if modulus == 0:
207 raise ZeroDivisionError("Division by zero")
208 if modulus < 0:
209 raise ValueError("Modulus must be positive")
210 self._value %= modulus
211 return self
212
213 # Boolean/bit operations
214 def __and__(self, term):
215 return self.__class__(self._value & int(term))
216
217 def __or__(self, term):
218 return self.__class__(self._value | int(term))
219
220 def __rshift__(self, pos):
221 try:
222 return self.__class__(self._value >> int(pos))
223 except OverflowError:
224 if self._value >= 0:
225 return 0
226 else:
227 return -1
228
229 def __irshift__(self, pos):
230 try:
231 self._value >>= int(pos)
232 except OverflowError:
233 if self._value >= 0:
234 return 0
235 else:
236 return -1
237 return self
238
239 def __lshift__(self, pos):
240 try:
241 return self.__class__(self._value << int(pos))
242 except OverflowError:
243 raise ValueError("Incorrect shift count")
244
245 def __ilshift__(self, pos):
246 try:
247 self._value <<= int(pos)
248 except OverflowError:
249 raise ValueError("Incorrect shift count")
250 return self
251
252 def get_bit(self, n):
253 if self._value < 0:
254 raise ValueError("no bit representation for negative values")
255 try:
256 try:
257 result = (self._value >> n._value) & 1
258 if n._value < 0:
259 raise ValueError("negative bit count")
260 except AttributeError:
261 result = (self._value >> n) & 1
262 if n < 0:
263 raise ValueError("negative bit count")
264 except OverflowError:
265 result = 0
266 return result
267
268 # Extra
269 def is_odd(self):
270 return (self._value & 1) == 1
271
272 def is_even(self):
273 return (self._value & 1) == 0
274
275 def size_in_bits(self):
276
277 if self._value < 0:
278 raise ValueError("Conversion only valid for non-negative numbers")
279
280 if self._value == 0:
281 return 1
282
283 return self._value.bit_length()
284
285 def size_in_bytes(self):
286 return (self.size_in_bits() - 1) // 8 + 1
287
288 def is_perfect_square(self):
289 if self._value < 0:
290 return False
291 if self._value in (0, 1):
292 return True
293
294 x = self._value // 2
295 square_x = x ** 2
296
297 while square_x > self._value:
298 x = (square_x + self._value) // (2 * x)
299 square_x = x ** 2
300
301 return self._value == x ** 2
302
303 def fail_if_divisible_by(self, small_prime):
304 if (self._value % int(small_prime)) == 0:
305 raise ValueError("Value is composite")
306
307 def multiply_accumulate(self, a, b):
308 self._value += int(a) * int(b)
309 return self
310
311 def set(self, source):
312 self._value = int(source)
313
314 def inplace_inverse(self, modulus):
315 self._value = inverse(self._value, int(modulus))
316 return self
317
318 def inverse(self, modulus):
319 result = self.__class__(self)
320 result.inplace_inverse(modulus)
321 return result
322
323 def gcd(self, term):
324 return self.__class__(GCD(abs(self._value), abs(int(term))))
325
326 def lcm(self, term):
327 term = int(term)
328 if self._value == 0 or term == 0:
329 return self.__class__(0)
330 return self.__class__(abs((self._value * term) // self.gcd(term)._value))
331
332 @staticmethod
333 def jacobi_symbol(a, n):
334 a = int(a)
335 n = int(n)
336
337 if n <= 0:
338 raise ValueError("n must be a positive integer")
339
340 if (n & 1) == 0:
341 raise ValueError("n must be odd for the Jacobi symbol")
342
343 # Step 1
344 a = a % n
345 # Step 2
346 if a == 1 or n == 1:
347 return 1
348 # Step 3
349 if a == 0:
350 return 0
351 # Step 4
352 e = 0
353 a1 = a
354 while (a1 & 1) == 0:
355 a1 >>= 1
356 e += 1
357 # Step 5
358 if (e & 1) == 0:
359 s = 1
360 elif n % 8 in (1, 7):
361 s = 1
362 else:
363 s = -1
364 # Step 6
365 if n % 4 == 3 and a1 % 4 == 3:
366 s = -s
367 # Step 7
368 n1 = n % a1
369 # Step 8
370 return s * IntegerNative.jacobi_symbol(n1, a1)
371
372 @staticmethod
373 def _mult_modulo_bytes(term1, term2, modulus):
374 if modulus < 0:
375 raise ValueError("Modulus must be positive")
376 if modulus == 0:
377 raise ZeroDivisionError("Modulus cannot be zero")
378 if (modulus & 1) == 0:
379 raise ValueError("Odd modulus is required")
380
381 number_len = len(long_to_bytes(modulus))
382 return long_to_bytes((term1 * term2) % modulus, number_len)