| 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 |
import sys |
| 32 |
|
| 33 |
from Crypto.Util.py3compat import tobytes, is_native_int |
| 34 |
|
| 35 |
from Crypto.Util._raw_api import (backend, load_lib, |
| 36 |
get_raw_buffer, get_c_string, |
| 37 |
null_pointer, create_string_buffer, |
| 38 |
c_ulong, c_size_t, c_uint8_ptr) |
| 39 |
|
| 40 |
from ._IntegerBase import IntegerBase |
| 41 |
|
| 42 |
gmp_defs = """typedef unsigned long UNIX_ULONG; |
| 43 |
typedef struct { int a; int b; void *c; } MPZ; |
| 44 |
typedef MPZ mpz_t[1]; |
| 45 |
typedef UNIX_ULONG mp_bitcnt_t; |
| 46 |
|
| 47 |
void __gmpz_init (mpz_t x); |
| 48 |
void __gmpz_init_set (mpz_t rop, const mpz_t op); |
| 49 |
void __gmpz_init_set_ui (mpz_t rop, UNIX_ULONG op); |
| 50 |
|
| 51 |
UNIX_ULONG __gmpz_get_ui (const mpz_t op); |
| 52 |
void __gmpz_set (mpz_t rop, const mpz_t op); |
| 53 |
void __gmpz_set_ui (mpz_t rop, UNIX_ULONG op); |
| 54 |
void __gmpz_add (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 55 |
void __gmpz_add_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2); |
| 56 |
void __gmpz_sub_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2); |
| 57 |
void __gmpz_addmul (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 58 |
void __gmpz_addmul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2); |
| 59 |
void __gmpz_submul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2); |
| 60 |
void __gmpz_import (mpz_t rop, size_t count, int order, size_t size, |
| 61 |
int endian, size_t nails, const void *op); |
| 62 |
void * __gmpz_export (void *rop, size_t *countp, int order, |
| 63 |
size_t size, |
| 64 |
int endian, size_t nails, const mpz_t op); |
| 65 |
size_t __gmpz_sizeinbase (const mpz_t op, int base); |
| 66 |
void __gmpz_sub (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 67 |
void __gmpz_mul (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 68 |
void __gmpz_mul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2); |
| 69 |
int __gmpz_cmp (const mpz_t op1, const mpz_t op2); |
| 70 |
void __gmpz_powm (mpz_t rop, const mpz_t base, const mpz_t exp, const |
| 71 |
mpz_t mod); |
| 72 |
void __gmpz_powm_ui (mpz_t rop, const mpz_t base, UNIX_ULONG exp, |
| 73 |
const mpz_t mod); |
| 74 |
void __gmpz_pow_ui (mpz_t rop, const mpz_t base, UNIX_ULONG exp); |
| 75 |
void __gmpz_sqrt(mpz_t rop, const mpz_t op); |
| 76 |
void __gmpz_mod (mpz_t r, const mpz_t n, const mpz_t d); |
| 77 |
void __gmpz_neg (mpz_t rop, const mpz_t op); |
| 78 |
void __gmpz_abs (mpz_t rop, const mpz_t op); |
| 79 |
void __gmpz_and (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 80 |
void __gmpz_ior (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 81 |
void __gmpz_clear (mpz_t x); |
| 82 |
void __gmpz_tdiv_q_2exp (mpz_t q, const mpz_t n, mp_bitcnt_t b); |
| 83 |
void __gmpz_fdiv_q (mpz_t q, const mpz_t n, const mpz_t d); |
| 84 |
void __gmpz_mul_2exp (mpz_t rop, const mpz_t op1, mp_bitcnt_t op2); |
| 85 |
int __gmpz_tstbit (const mpz_t op, mp_bitcnt_t bit_index); |
| 86 |
int __gmpz_perfect_square_p (const mpz_t op); |
| 87 |
int __gmpz_jacobi (const mpz_t a, const mpz_t b); |
| 88 |
void __gmpz_gcd (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 89 |
UNIX_ULONG __gmpz_gcd_ui (mpz_t rop, const mpz_t op1, |
| 90 |
UNIX_ULONG op2); |
| 91 |
void __gmpz_lcm (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 92 |
int __gmpz_invert (mpz_t rop, const mpz_t op1, const mpz_t op2); |
| 93 |
int __gmpz_divisible_p (const mpz_t n, const mpz_t d); |
| 94 |
int __gmpz_divisible_ui_p (const mpz_t n, UNIX_ULONG d); |
| 95 |
""" |
| 96 |
|
| 97 |
if sys.platform == "win32": |
| 98 |
raise ImportError("Not using GMP on Windows") |
| 99 |
|
| 100 |
lib = load_lib("gmp", gmp_defs) |
| 101 |
implementation = {"library": "gmp", "api": backend} |
| 102 |
|
| 103 |
if hasattr(lib, "__mpir_version"): |
| 104 |
raise ImportError("MPIR library detected") |
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
if implementation["api"] == "ctypes": |
| 110 |
from ctypes import Structure, c_int, c_void_p, byref |
| 111 |
|
| 112 |
class _MPZ(Structure): |
| 113 |
_fields_ = [('_mp_alloc', c_int), |
| 114 |
('_mp_size', c_int), |
| 115 |
('_mp_d', c_void_p)] |
| 116 |
|
| 117 |
def new_mpz(): |
| 118 |
return byref(_MPZ()) |
| 119 |
|
| 120 |
else: |
| 121 |
|
| 122 |
from Crypto.Util._raw_api import ffi |
| 123 |
|
| 124 |
def new_mpz(): |
| 125 |
return ffi.new("MPZ*") |
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
class _GMP(object): |
| 130 |
|
| 131 |
def __getattr__(self, name): |
| 132 |
if name.startswith("mpz_"): |
| 133 |
func_name = "__gmpz_" + name[4:] |
| 134 |
elif name.startswith("gmp_"): |
| 135 |
func_name = "__gmp_" + name[4:] |
| 136 |
else: |
| 137 |
raise AttributeError("Attribute %s is invalid" % name) |
| 138 |
func = getattr(lib, func_name) |
| 139 |
setattr(self, name, func) |
| 140 |
return func |
| 141 |
|
| 142 |
|
| 143 |
_gmp = _GMP() |
| 144 |
|
| 145 |
|
| 146 |
class IntegerGMP(IntegerBase): |
| 147 |
"""A fast, arbitrary precision integer""" |
| 148 |
|
| 149 |
_zero_mpz_p = new_mpz() |
| 150 |
_gmp.mpz_init_set_ui(_zero_mpz_p, c_ulong(0)) |
| 151 |
|
| 152 |
def __init__(self, value): |
| 153 |
"""Initialize the integer to the given value.""" |
| 154 |
|
| 155 |
self._mpz_p = new_mpz() |
| 156 |
self._initialized = False |
| 157 |
|
| 158 |
if isinstance(value, float): |
| 159 |
raise ValueError("A floating point type is not a natural number") |
| 160 |
|
| 161 |
if is_native_int(value): |
| 162 |
_gmp.mpz_init(self._mpz_p) |
| 163 |
self._initialized = True |
| 164 |
if value == 0: |
| 165 |
return |
| 166 |
|
| 167 |
tmp = new_mpz() |
| 168 |
_gmp.mpz_init(tmp) |
| 169 |
|
| 170 |
try: |
| 171 |
positive = value >= 0 |
| 172 |
reduce = abs(value) |
| 173 |
slots = (reduce.bit_length() - 1) // 32 + 1 |
| 174 |
|
| 175 |
while slots > 0: |
| 176 |
slots = slots - 1 |
| 177 |
_gmp.mpz_set_ui(tmp, |
| 178 |
c_ulong(0xFFFFFFFF & (reduce >> (slots * 32)))) |
| 179 |
_gmp.mpz_mul_2exp(tmp, tmp, c_ulong(slots * 32)) |
| 180 |
_gmp.mpz_add(self._mpz_p, self._mpz_p, tmp) |
| 181 |
finally: |
| 182 |
_gmp.mpz_clear(tmp) |
| 183 |
|
| 184 |
if not positive: |
| 185 |
_gmp.mpz_neg(self._mpz_p, self._mpz_p) |
| 186 |
|
| 187 |
elif isinstance(value, IntegerGMP): |
| 188 |
_gmp.mpz_init_set(self._mpz_p, value._mpz_p) |
| 189 |
self._initialized = True |
| 190 |
else: |
| 191 |
raise NotImplementedError |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
def __int__(self): |
| 196 |
tmp = new_mpz() |
| 197 |
_gmp.mpz_init_set(tmp, self._mpz_p) |
| 198 |
|
| 199 |
try: |
| 200 |
value = 0 |
| 201 |
slot = 0 |
| 202 |
while _gmp.mpz_cmp(tmp, self._zero_mpz_p) != 0: |
| 203 |
lsb = _gmp.mpz_get_ui(tmp) & 0xFFFFFFFF |
| 204 |
value |= lsb << (slot * 32) |
| 205 |
_gmp.mpz_tdiv_q_2exp(tmp, tmp, c_ulong(32)) |
| 206 |
slot = slot + 1 |
| 207 |
finally: |
| 208 |
_gmp.mpz_clear(tmp) |
| 209 |
|
| 210 |
if self < 0: |
| 211 |
value = -value |
| 212 |
return int(value) |
| 213 |
|
| 214 |
def __str__(self): |
| 215 |
return str(int(self)) |
| 216 |
|
| 217 |
def __repr__(self): |
| 218 |
return "Integer(%s)" % str(self) |
| 219 |
|
| 220 |
|
| 221 |
def __hex__(self): |
| 222 |
return hex(int(self)) |
| 223 |
|
| 224 |
|
| 225 |
def __index__(self): |
| 226 |
return int(self) |
| 227 |
|
| 228 |
def to_bytes(self, block_size=0, byteorder='big'): |
| 229 |
"""Convert the number into a byte string. |
| 230 |
|
| 231 |
This method encodes the number in network order and prepends |
| 232 |
as many zero bytes as required. It only works for non-negative |
| 233 |
values. |
| 234 |
|
| 235 |
:Parameters: |
| 236 |
block_size : integer |
| 237 |
The exact size the output byte string must have. |
| 238 |
If zero, the string has the minimal length. |
| 239 |
byteorder : string |
| 240 |
'big' for big-endian integers (default), 'little' for litte-endian. |
| 241 |
:Returns: |
| 242 |
A byte string. |
| 243 |
:Raise ValueError: |
| 244 |
If the value is negative or if ``block_size`` is |
| 245 |
provided and the length of the byte string would exceed it. |
| 246 |
""" |
| 247 |
|
| 248 |
if self < 0: |
| 249 |
raise ValueError("Conversion only valid for non-negative numbers") |
| 250 |
|
| 251 |
buf_len = (_gmp.mpz_sizeinbase(self._mpz_p, 2) + 7) // 8 |
| 252 |
if buf_len > block_size > 0: |
| 253 |
raise ValueError("Number is too big to convert to byte string" |
| 254 |
" of prescribed length") |
| 255 |
buf = create_string_buffer(buf_len) |
| 256 |
|
| 257 |
|
| 258 |
_gmp.mpz_export( |
| 259 |
buf, |
| 260 |
null_pointer, |
| 261 |
1, |
| 262 |
c_size_t(1), |
| 263 |
0, |
| 264 |
c_size_t(0), |
| 265 |
self._mpz_p) |
| 266 |
|
| 267 |
result = b'\x00' * max(0, block_size - buf_len) + get_raw_buffer(buf) |
| 268 |
if byteorder == 'big': |
| 269 |
pass |
| 270 |
elif byteorder == 'little': |
| 271 |
result = bytearray(result) |
| 272 |
result.reverse() |
| 273 |
result = bytes(result) |
| 274 |
else: |
| 275 |
raise ValueError("Incorrect byteorder") |
| 276 |
return result |
| 277 |
|
| 278 |
@staticmethod |
| 279 |
def from_bytes(byte_string, byteorder='big'): |
| 280 |
"""Convert a byte string into a number. |
| 281 |
|
| 282 |
:Parameters: |
| 283 |
byte_string : byte string |
| 284 |
The input number, encoded in network order. |
| 285 |
It can only be non-negative. |
| 286 |
byteorder : string |
| 287 |
'big' for big-endian integers (default), 'little' for litte-endian. |
| 288 |
|
| 289 |
:Return: |
| 290 |
The ``Integer`` object carrying the same value as the input. |
| 291 |
""" |
| 292 |
result = IntegerGMP(0) |
| 293 |
if byteorder == 'big': |
| 294 |
pass |
| 295 |
elif byteorder == 'little': |
| 296 |
byte_string = bytearray(byte_string) |
| 297 |
byte_string.reverse() |
| 298 |
else: |
| 299 |
raise ValueError("Incorrect byteorder") |
| 300 |
_gmp.mpz_import( |
| 301 |
result._mpz_p, |
| 302 |
c_size_t(len(byte_string)), |
| 303 |
1, |
| 304 |
c_size_t(1), |
| 305 |
0, |
| 306 |
c_size_t(0), |
| 307 |
c_uint8_ptr(byte_string)) |
| 308 |
return result |
| 309 |
|
| 310 |
|
| 311 |
def _apply_and_return(self, func, term): |
| 312 |
if not isinstance(term, IntegerGMP): |
| 313 |
term = IntegerGMP(term) |
| 314 |
return func(self._mpz_p, term._mpz_p) |
| 315 |
|
| 316 |
def __eq__(self, term): |
| 317 |
if not (isinstance(term, IntegerGMP) or is_native_int(term)): |
| 318 |
return False |
| 319 |
return self._apply_and_return(_gmp.mpz_cmp, term) == 0 |
| 320 |
|
| 321 |
def __ne__(self, term): |
| 322 |
if not (isinstance(term, IntegerGMP) or is_native_int(term)): |
| 323 |
return True |
| 324 |
return self._apply_and_return(_gmp.mpz_cmp, term) != 0 |
| 325 |
|
| 326 |
def __lt__(self, term): |
| 327 |
return self._apply_and_return(_gmp.mpz_cmp, term) < 0 |
| 328 |
|
| 329 |
def __le__(self, term): |
| 330 |
return self._apply_and_return(_gmp.mpz_cmp, term) <= 0 |
| 331 |
|
| 332 |
def __gt__(self, term): |
| 333 |
return self._apply_and_return(_gmp.mpz_cmp, term) > 0 |
| 334 |
|
| 335 |
def __ge__(self, term): |
| 336 |
return self._apply_and_return(_gmp.mpz_cmp, term) >= 0 |
| 337 |
|
| 338 |
def __nonzero__(self): |
| 339 |
return _gmp.mpz_cmp(self._mpz_p, self._zero_mpz_p) != 0 |
| 340 |
__bool__ = __nonzero__ |
| 341 |
|
| 342 |
def is_negative(self): |
| 343 |
return _gmp.mpz_cmp(self._mpz_p, self._zero_mpz_p) < 0 |
| 344 |
|
| 345 |
|
| 346 |
def __add__(self, term): |
| 347 |
result = IntegerGMP(0) |
| 348 |
if not isinstance(term, IntegerGMP): |
| 349 |
try: |
| 350 |
term = IntegerGMP(term) |
| 351 |
except NotImplementedError: |
| 352 |
return NotImplemented |
| 353 |
_gmp.mpz_add(result._mpz_p, |
| 354 |
self._mpz_p, |
| 355 |
term._mpz_p) |
| 356 |
return result |
| 357 |
|
| 358 |
def __sub__(self, term): |
| 359 |
result = IntegerGMP(0) |
| 360 |
if not isinstance(term, IntegerGMP): |
| 361 |
try: |
| 362 |
term = IntegerGMP(term) |
| 363 |
except NotImplementedError: |
| 364 |
return NotImplemented |
| 365 |
_gmp.mpz_sub(result._mpz_p, |
| 366 |
self._mpz_p, |
| 367 |
term._mpz_p) |
| 368 |
return result |
| 369 |
|
| 370 |
def __mul__(self, term): |
| 371 |
result = IntegerGMP(0) |
| 372 |
if not isinstance(term, IntegerGMP): |
| 373 |
try: |
| 374 |
term = IntegerGMP(term) |
| 375 |
except NotImplementedError: |
| 376 |
return NotImplemented |
| 377 |
_gmp.mpz_mul(result._mpz_p, |
| 378 |
self._mpz_p, |
| 379 |
term._mpz_p) |
| 380 |
return result |
| 381 |
|
| 382 |
def __floordiv__(self, divisor): |
| 383 |
if not isinstance(divisor, IntegerGMP): |
| 384 |
divisor = IntegerGMP(divisor) |
| 385 |
if _gmp.mpz_cmp(divisor._mpz_p, |
| 386 |
self._zero_mpz_p) == 0: |
| 387 |
raise ZeroDivisionError("Division by zero") |
| 388 |
result = IntegerGMP(0) |
| 389 |
_gmp.mpz_fdiv_q(result._mpz_p, |
| 390 |
self._mpz_p, |
| 391 |
divisor._mpz_p) |
| 392 |
return result |
| 393 |
|
| 394 |
def __mod__(self, divisor): |
| 395 |
if not isinstance(divisor, IntegerGMP): |
| 396 |
divisor = IntegerGMP(divisor) |
| 397 |
comp = _gmp.mpz_cmp(divisor._mpz_p, |
| 398 |
self._zero_mpz_p) |
| 399 |
if comp == 0: |
| 400 |
raise ZeroDivisionError("Division by zero") |
| 401 |
if comp < 0: |
| 402 |
raise ValueError("Modulus must be positive") |
| 403 |
result = IntegerGMP(0) |
| 404 |
_gmp.mpz_mod(result._mpz_p, |
| 405 |
self._mpz_p, |
| 406 |
divisor._mpz_p) |
| 407 |
return result |
| 408 |
|
| 409 |
def inplace_pow(self, exponent, modulus=None): |
| 410 |
|
| 411 |
if modulus is None: |
| 412 |
if exponent < 0: |
| 413 |
raise ValueError("Exponent must not be negative") |
| 414 |
|
| 415 |
|
| 416 |
if exponent > 256: |
| 417 |
raise ValueError("Exponent is too big") |
| 418 |
_gmp.mpz_pow_ui(self._mpz_p, |
| 419 |
self._mpz_p, |
| 420 |
c_ulong(int(exponent)) |
| 421 |
) |
| 422 |
else: |
| 423 |
|
| 424 |
if not isinstance(modulus, IntegerGMP): |
| 425 |
modulus = IntegerGMP(modulus) |
| 426 |
if not modulus: |
| 427 |
raise ZeroDivisionError("Division by zero") |
| 428 |
if modulus.is_negative(): |
| 429 |
raise ValueError("Modulus must be positive") |
| 430 |
if is_native_int(exponent): |
| 431 |
if exponent < 0: |
| 432 |
raise ValueError("Exponent must not be negative") |
| 433 |
if exponent < 65536: |
| 434 |
_gmp.mpz_powm_ui(self._mpz_p, |
| 435 |
self._mpz_p, |
| 436 |
c_ulong(exponent), |
| 437 |
modulus._mpz_p) |
| 438 |
return self |
| 439 |
exponent = IntegerGMP(exponent) |
| 440 |
elif exponent.is_negative(): |
| 441 |
raise ValueError("Exponent must not be negative") |
| 442 |
_gmp.mpz_powm(self._mpz_p, |
| 443 |
self._mpz_p, |
| 444 |
exponent._mpz_p, |
| 445 |
modulus._mpz_p) |
| 446 |
return self |
| 447 |
|
| 448 |
def __pow__(self, exponent, modulus=None): |
| 449 |
result = IntegerGMP(self) |
| 450 |
return result.inplace_pow(exponent, modulus) |
| 451 |
|
| 452 |
def __abs__(self): |
| 453 |
result = IntegerGMP(0) |
| 454 |
_gmp.mpz_abs(result._mpz_p, self._mpz_p) |
| 455 |
return result |
| 456 |
|
| 457 |
def sqrt(self, modulus=None): |
| 458 |
"""Return the largest Integer that does not |
| 459 |
exceed the square root""" |
| 460 |
|
| 461 |
if modulus is None: |
| 462 |
if self < 0: |
| 463 |
raise ValueError("Square root of negative value") |
| 464 |
result = IntegerGMP(0) |
| 465 |
_gmp.mpz_sqrt(result._mpz_p, |
| 466 |
self._mpz_p) |
| 467 |
else: |
| 468 |
if modulus <= 0: |
| 469 |
raise ValueError("Modulus must be positive") |
| 470 |
modulus = int(modulus) |
| 471 |
result = IntegerGMP(self._tonelli_shanks(int(self) % modulus, modulus)) |
| 472 |
|
| 473 |
return result |
| 474 |
|
| 475 |
def __iadd__(self, term): |
| 476 |
if is_native_int(term): |
| 477 |
if 0 <= term < 65536: |
| 478 |
_gmp.mpz_add_ui(self._mpz_p, |
| 479 |
self._mpz_p, |
| 480 |
c_ulong(term)) |
| 481 |
return self |
| 482 |
if -65535 < term < 0: |
| 483 |
_gmp.mpz_sub_ui(self._mpz_p, |
| 484 |
self._mpz_p, |
| 485 |
c_ulong(-term)) |
| 486 |
return self |
| 487 |
term = IntegerGMP(term) |
| 488 |
_gmp.mpz_add(self._mpz_p, |
| 489 |
self._mpz_p, |
| 490 |
term._mpz_p) |
| 491 |
return self |
| 492 |
|
| 493 |
def __isub__(self, term): |
| 494 |
if is_native_int(term): |
| 495 |
if 0 <= term < 65536: |
| 496 |
_gmp.mpz_sub_ui(self._mpz_p, |
| 497 |
self._mpz_p, |
| 498 |
c_ulong(term)) |
| 499 |
return self |
| 500 |
if -65535 < term < 0: |
| 501 |
_gmp.mpz_add_ui(self._mpz_p, |
| 502 |
self._mpz_p, |
| 503 |
c_ulong(-term)) |
| 504 |
return self |
| 505 |
term = IntegerGMP(term) |
| 506 |
_gmp.mpz_sub(self._mpz_p, |
| 507 |
self._mpz_p, |
| 508 |
term._mpz_p) |
| 509 |
return self |
| 510 |
|
| 511 |
def __imul__(self, term): |
| 512 |
if is_native_int(term): |
| 513 |
if 0 <= term < 65536: |
| 514 |
_gmp.mpz_mul_ui(self._mpz_p, |
| 515 |
self._mpz_p, |
| 516 |
c_ulong(term)) |
| 517 |
return self |
| 518 |
if -65535 < term < 0: |
| 519 |
_gmp.mpz_mul_ui(self._mpz_p, |
| 520 |
self._mpz_p, |
| 521 |
c_ulong(-term)) |
| 522 |
_gmp.mpz_neg(self._mpz_p, self._mpz_p) |
| 523 |
return self |
| 524 |
term = IntegerGMP(term) |
| 525 |
_gmp.mpz_mul(self._mpz_p, |
| 526 |
self._mpz_p, |
| 527 |
term._mpz_p) |
| 528 |
return self |
| 529 |
|
| 530 |
def __imod__(self, divisor): |
| 531 |
if not isinstance(divisor, IntegerGMP): |
| 532 |
divisor = IntegerGMP(divisor) |
| 533 |
comp = _gmp.mpz_cmp(divisor._mpz_p, |
| 534 |
divisor._zero_mpz_p) |
| 535 |
if comp == 0: |
| 536 |
raise ZeroDivisionError("Division by zero") |
| 537 |
if comp < 0: |
| 538 |
raise ValueError("Modulus must be positive") |
| 539 |
_gmp.mpz_mod(self._mpz_p, |
| 540 |
self._mpz_p, |
| 541 |
divisor._mpz_p) |
| 542 |
return self |
| 543 |
|
| 544 |
|
| 545 |
def __and__(self, term): |
| 546 |
result = IntegerGMP(0) |
| 547 |
if not isinstance(term, IntegerGMP): |
| 548 |
term = IntegerGMP(term) |
| 549 |
_gmp.mpz_and(result._mpz_p, |
| 550 |
self._mpz_p, |
| 551 |
term._mpz_p) |
| 552 |
return result |
| 553 |
|
| 554 |
def __or__(self, term): |
| 555 |
result = IntegerGMP(0) |
| 556 |
if not isinstance(term, IntegerGMP): |
| 557 |
term = IntegerGMP(term) |
| 558 |
_gmp.mpz_ior(result._mpz_p, |
| 559 |
self._mpz_p, |
| 560 |
term._mpz_p) |
| 561 |
return result |
| 562 |
|
| 563 |
def __rshift__(self, pos): |
| 564 |
result = IntegerGMP(0) |
| 565 |
if pos < 0: |
| 566 |
raise ValueError("negative shift count") |
| 567 |
if pos > 65536: |
| 568 |
if self < 0: |
| 569 |
return -1 |
| 570 |
else: |
| 571 |
return 0 |
| 572 |
_gmp.mpz_tdiv_q_2exp(result._mpz_p, |
| 573 |
self._mpz_p, |
| 574 |
c_ulong(int(pos))) |
| 575 |
return result |
| 576 |
|
| 577 |
def __irshift__(self, pos): |
| 578 |
if pos < 0: |
| 579 |
raise ValueError("negative shift count") |
| 580 |
if pos > 65536: |
| 581 |
if self < 0: |
| 582 |
return -1 |
| 583 |
else: |
| 584 |
return 0 |
| 585 |
_gmp.mpz_tdiv_q_2exp(self._mpz_p, |
| 586 |
self._mpz_p, |
| 587 |
c_ulong(int(pos))) |
| 588 |
return self |
| 589 |
|
| 590 |
def __lshift__(self, pos): |
| 591 |
result = IntegerGMP(0) |
| 592 |
if not 0 <= pos < 65536: |
| 593 |
raise ValueError("Incorrect shift count") |
| 594 |
_gmp.mpz_mul_2exp(result._mpz_p, |
| 595 |
self._mpz_p, |
| 596 |
c_ulong(int(pos))) |
| 597 |
return result |
| 598 |
|
| 599 |
def __ilshift__(self, pos): |
| 600 |
if not 0 <= pos < 65536: |
| 601 |
raise ValueError("Incorrect shift count") |
| 602 |
_gmp.mpz_mul_2exp(self._mpz_p, |
| 603 |
self._mpz_p, |
| 604 |
c_ulong(int(pos))) |
| 605 |
return self |
| 606 |
|
| 607 |
def get_bit(self, n): |
| 608 |
"""Return True if the n-th bit is set to 1. |
| 609 |
Bit 0 is the least significant.""" |
| 610 |
|
| 611 |
if self < 0: |
| 612 |
raise ValueError("no bit representation for negative values") |
| 613 |
if n < 0: |
| 614 |
raise ValueError("negative bit count") |
| 615 |
if n > 65536: |
| 616 |
return 0 |
| 617 |
return bool(_gmp.mpz_tstbit(self._mpz_p, |
| 618 |
c_ulong(int(n)))) |
| 619 |
|
| 620 |
|
| 621 |
def is_odd(self): |
| 622 |
return _gmp.mpz_tstbit(self._mpz_p, 0) == 1 |
| 623 |
|
| 624 |
def is_even(self): |
| 625 |
return _gmp.mpz_tstbit(self._mpz_p, 0) == 0 |
| 626 |
|
| 627 |
def size_in_bits(self): |
| 628 |
"""Return the minimum number of bits that can encode the number.""" |
| 629 |
|
| 630 |
if self < 0: |
| 631 |
raise ValueError("Conversion only valid for non-negative numbers") |
| 632 |
return _gmp.mpz_sizeinbase(self._mpz_p, 2) |
| 633 |
|
| 634 |
def size_in_bytes(self): |
| 635 |
"""Return the minimum number of bytes that can encode the number.""" |
| 636 |
return (self.size_in_bits() - 1) // 8 + 1 |
| 637 |
|
| 638 |
def is_perfect_square(self): |
| 639 |
return _gmp.mpz_perfect_square_p(self._mpz_p) != 0 |
| 640 |
|
| 641 |
def fail_if_divisible_by(self, small_prime): |
| 642 |
"""Raise an exception if the small prime is a divisor.""" |
| 643 |
|
| 644 |
if is_native_int(small_prime): |
| 645 |
if 0 < small_prime < 65536: |
| 646 |
if _gmp.mpz_divisible_ui_p(self._mpz_p, |
| 647 |
c_ulong(small_prime)): |
| 648 |
raise ValueError("The value is composite") |
| 649 |
return |
| 650 |
small_prime = IntegerGMP(small_prime) |
| 651 |
if _gmp.mpz_divisible_p(self._mpz_p, |
| 652 |
small_prime._mpz_p): |
| 653 |
raise ValueError("The value is composite") |
| 654 |
|
| 655 |
def multiply_accumulate(self, a, b): |
| 656 |
"""Increment the number by the product of a and b.""" |
| 657 |
|
| 658 |
if not isinstance(a, IntegerGMP): |
| 659 |
a = IntegerGMP(a) |
| 660 |
if is_native_int(b): |
| 661 |
if 0 < b < 65536: |
| 662 |
_gmp.mpz_addmul_ui(self._mpz_p, |
| 663 |
a._mpz_p, |
| 664 |
c_ulong(b)) |
| 665 |
return self |
| 666 |
if -65535 < b < 0: |
| 667 |
_gmp.mpz_submul_ui(self._mpz_p, |
| 668 |
a._mpz_p, |
| 669 |
c_ulong(-b)) |
| 670 |
return self |
| 671 |
b = IntegerGMP(b) |
| 672 |
_gmp.mpz_addmul(self._mpz_p, |
| 673 |
a._mpz_p, |
| 674 |
b._mpz_p) |
| 675 |
return self |
| 676 |
|
| 677 |
def set(self, source): |
| 678 |
"""Set the Integer to have the given value""" |
| 679 |
|
| 680 |
if not isinstance(source, IntegerGMP): |
| 681 |
source = IntegerGMP(source) |
| 682 |
_gmp.mpz_set(self._mpz_p, |
| 683 |
source._mpz_p) |
| 684 |
return self |
| 685 |
|
| 686 |
def inplace_inverse(self, modulus): |
| 687 |
"""Compute the inverse of this number in the ring of |
| 688 |
modulo integers. |
| 689 |
|
| 690 |
Raise an exception if no inverse exists. |
| 691 |
""" |
| 692 |
|
| 693 |
if not isinstance(modulus, IntegerGMP): |
| 694 |
modulus = IntegerGMP(modulus) |
| 695 |
|
| 696 |
comp = _gmp.mpz_cmp(modulus._mpz_p, |
| 697 |
self._zero_mpz_p) |
| 698 |
if comp == 0: |
| 699 |
raise ZeroDivisionError("Modulus cannot be zero") |
| 700 |
if comp < 0: |
| 701 |
raise ValueError("Modulus must be positive") |
| 702 |
|
| 703 |
result = _gmp.mpz_invert(self._mpz_p, |
| 704 |
self._mpz_p, |
| 705 |
modulus._mpz_p) |
| 706 |
if not result: |
| 707 |
raise ValueError("No inverse value can be computed") |
| 708 |
return self |
| 709 |
|
| 710 |
def inverse(self, modulus): |
| 711 |
result = IntegerGMP(self) |
| 712 |
result.inplace_inverse(modulus) |
| 713 |
return result |
| 714 |
|
| 715 |
def gcd(self, term): |
| 716 |
"""Compute the greatest common denominator between this |
| 717 |
number and another term.""" |
| 718 |
|
| 719 |
result = IntegerGMP(0) |
| 720 |
if is_native_int(term): |
| 721 |
if 0 < term < 65535: |
| 722 |
_gmp.mpz_gcd_ui(result._mpz_p, |
| 723 |
self._mpz_p, |
| 724 |
c_ulong(term)) |
| 725 |
return result |
| 726 |
term = IntegerGMP(term) |
| 727 |
_gmp.mpz_gcd(result._mpz_p, self._mpz_p, term._mpz_p) |
| 728 |
return result |
| 729 |
|
| 730 |
def lcm(self, term): |
| 731 |
"""Compute the least common multiplier between this |
| 732 |
number and another term.""" |
| 733 |
|
| 734 |
result = IntegerGMP(0) |
| 735 |
if not isinstance(term, IntegerGMP): |
| 736 |
term = IntegerGMP(term) |
| 737 |
_gmp.mpz_lcm(result._mpz_p, self._mpz_p, term._mpz_p) |
| 738 |
return result |
| 739 |
|
| 740 |
@staticmethod |
| 741 |
def jacobi_symbol(a, n): |
| 742 |
"""Compute the Jacobi symbol""" |
| 743 |
|
| 744 |
if not isinstance(a, IntegerGMP): |
| 745 |
a = IntegerGMP(a) |
| 746 |
if not isinstance(n, IntegerGMP): |
| 747 |
n = IntegerGMP(n) |
| 748 |
if n <= 0 or n.is_even(): |
| 749 |
raise ValueError("n must be positive odd for the Jacobi symbol") |
| 750 |
return _gmp.mpz_jacobi(a._mpz_p, n._mpz_p) |
| 751 |
|
| 752 |
@staticmethod |
| 753 |
def _mult_modulo_bytes(term1, term2, modulus): |
| 754 |
if not isinstance(term1, IntegerGMP): |
| 755 |
term1 = IntegerGMP(term1) |
| 756 |
if not isinstance(term2, IntegerGMP): |
| 757 |
term2 = IntegerGMP(term2) |
| 758 |
if not isinstance(modulus, IntegerGMP): |
| 759 |
modulus = IntegerGMP(modulus) |
| 760 |
|
| 761 |
if modulus < 0: |
| 762 |
raise ValueError("Modulus must be positive") |
| 763 |
if modulus == 0: |
| 764 |
raise ZeroDivisionError("Modulus cannot be zero") |
| 765 |
if (modulus & 1) == 0: |
| 766 |
raise ValueError("Odd modulus is required") |
| 767 |
|
| 768 |
numbers_len = len(modulus.to_bytes()) |
| 769 |
result = ((term1 * term2) % modulus).to_bytes(numbers_len) |
| 770 |
return result |
| 771 |
|
| 772 |
|
| 773 |
def __del__(self): |
| 774 |
|
| 775 |
try: |
| 776 |
if self._mpz_p is not None: |
| 777 |
if self._initialized: |
| 778 |
_gmp.mpz_clear(self._mpz_p) |
| 779 |
|
| 780 |
self._mpz_p = None |
| 781 |
except AttributeError: |
| 782 |
pass |