_IntegerNative.py 11 KB

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