Updated DB_Helper by adding firebase methods.

This commit is contained in:
Batuhan Berk Başoğlu 2020-10-05 16:53:40 -04:00
parent 485cc3bbba
commit c82121d036
1810 changed files with 537281 additions and 1 deletions

View file

@ -0,0 +1,145 @@
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
"""Fast, arbitrary precision integers.
:undocumented: __package__
"""
__all__ = ["Integer"]
from Crypto.Util.py3compat import *
from Crypto import Random
try:
from Crypto.Math._Numbers_gmp import Integer
from Crypto.Math._Numbers_gmp import implementation as _implementation
except (ImportError, OSError):
from Crypto.Math._Numbers_int import Integer
_implementation = { }
def _random(**kwargs):
"""Generate a random natural integer of a certain size.
:Keywords:
exact_bits : positive integer
The length in bits of the resulting random Integer number.
The number is guaranteed to fulfil the relation:
2^bits > result >= 2^(bits - 1)
max_bits : positive integer
The maximum length in bits of the resulting random Integer number.
The number is guaranteed to fulfil the relation:
2^bits > result >=0
randfunc : callable
A function that returns a random byte string. The length of the
byte string is passed as parameter. Optional.
If not provided (or ``None``), randomness is read from the system RNG.
:Return: a Integer object
"""
exact_bits = kwargs.pop("exact_bits", None)
max_bits = kwargs.pop("max_bits", None)
randfunc = kwargs.pop("randfunc", None)
if randfunc is None:
randfunc = Random.new().read
if exact_bits is None and max_bits is None:
raise ValueError("Either 'exact_bits' or 'max_bits' must be specified")
if exact_bits is not None and max_bits is not None:
raise ValueError("'exact_bits' and 'max_bits' are mutually exclusive")
bits = exact_bits or max_bits
bytes_needed = ((bits - 1) // 8) + 1
significant_bits_msb = 8 - (bytes_needed * 8 - bits)
msb = bord(randfunc(1)[0])
if exact_bits is not None:
msb |= 1 << (significant_bits_msb - 1)
msb &= (1 << significant_bits_msb) - 1
return Integer.from_bytes(bchr(msb) + randfunc(bytes_needed - 1))
def _random_range(**kwargs):
"""Generate a random integer within a given internal.
:Keywords:
min_inclusive : integer
The lower end of the interval (inclusive).
max_inclusive : integer
The higher end of the interval (inclusive).
max_exclusive : integer
The higher end of the interval (exclusive).
randfunc : callable
A function that returns a random byte string. The length of the
byte string is passed as parameter. Optional.
If not provided (or ``None``), randomness is read from the system RNG.
:Returns:
An Integer randomly taken in the given interval.
"""
min_inclusive = kwargs.pop("min_inclusive", None)
max_inclusive = kwargs.pop("max_inclusive", None)
max_exclusive = kwargs.pop("max_exclusive", None)
randfunc = kwargs.pop("randfunc", None)
if kwargs:
raise ValueError("Unknown keywords: " + str(kwargs.keys))
if None not in (max_inclusive, max_exclusive):
raise ValueError("max_inclusive and max_exclusive cannot be both"
" specified")
if max_exclusive is not None:
max_inclusive = max_exclusive - 1
if None in (min_inclusive, max_inclusive):
raise ValueError("Missing keyword to identify the interval")
if randfunc is None:
randfunc = Random.new().read
norm_maximum = max_inclusive - min_inclusive
bits_needed = Integer(norm_maximum).size_in_bits()
norm_candidate = -1
while not 0 <= norm_candidate <= norm_maximum:
norm_candidate = _random(
max_bits=bits_needed,
randfunc=randfunc
)
return norm_candidate + min_inclusive
Integer.random = staticmethod(_random)
Integer.random_range = staticmethod(_random_range)

View file

@ -0,0 +1,355 @@
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
"""Functions to create and test prime numbers.
:undocumented: __package__
"""
from Crypto.Math.Numbers import Integer
from Crypto import Random
COMPOSITE = 0
PROBABLY_PRIME = 1
def miller_rabin_test(candidate, iterations, randfunc=None):
"""Perform a Miller-Rabin primality test on an integer.
The test is specified in Section C.3.1 of `FIPS PUB 186-4`__.
:Parameters:
candidate : integer
The number to test for primality.
iterations : integer
The maximum number of iterations to perform before
declaring a candidate a probable prime.
randfunc : callable
An RNG function where bases are taken from.
:Returns:
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
if candidate.is_even():
return COMPOSITE
one = Integer(1)
minus_one = Integer(candidate - 1)
if randfunc is None:
randfunc = Random.new().read
# Step 1 and 2
m = Integer(minus_one)
a = 0
while m.is_even():
m >>= 1
a += 1
# Skip step 3
# Step 4
for i in range(iterations):
# Step 4.1-2
base = 1
while base in (one, minus_one):
base = Integer.random_range(min_inclusive=2,
max_inclusive=candidate - 2)
assert(2 <= base <= candidate - 2)
# Step 4.3-4.4
z = pow(base, m, candidate)
if z in (one, minus_one):
continue
# Step 4.5
for j in range(1, a):
z = pow(z, 2, candidate)
if z == minus_one:
break
if z == one:
return COMPOSITE
else:
return COMPOSITE
# Step 5
return PROBABLY_PRIME
def lucas_test(candidate):
"""Perform a Lucas primality test on an integer.
The test is specified in Section C.3.3 of `FIPS PUB 186-4`__.
:Parameters:
candidate : integer
The number to test for primality.
:Returns:
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
# Step 1
if candidate.is_even() or candidate.is_perfect_square():
return COMPOSITE
# Step 2
def alternate():
sgn = 1
value = 5
for x in range(10):
yield sgn * value
sgn, value = -sgn, value + 2
for D in alternate():
js = Integer.jacobi_symbol(D, candidate)
if js == 0:
return COMPOSITE
if js == -1:
break
else:
return COMPOSITE
# Found D. P=1 and Q=(1-D)/4 (note that Q is guaranteed to be an integer)
# Step 3
# This is \delta(n) = n - jacobi(D/n)
K = candidate + 1
# Step 4
r = K.size_in_bits() - 1
# Step 5
# U_1=1 and V_1=P
U_i = Integer(1)
V_i = Integer(1)
U_temp = Integer(0)
V_temp = Integer(0)
# Step 6
for i in range(r - 1, -1, -1):
# Square
# U_temp = U_i * V_i % candidate
U_temp.set(U_i)
U_temp *= V_i
U_temp %= candidate
# V_temp = (((V_i ** 2 + (U_i ** 2 * D)) * K) >> 1) % candidate
V_temp.set(U_i)
V_temp *= U_i
V_temp *= D
V_temp.multiply_accumulate(V_i, V_i)
if V_temp.is_odd():
V_temp += candidate
V_temp >>= 1
V_temp %= candidate
# Multiply
if K.get_bit(i):
# U_i = (((U_temp + V_temp) * K) >> 1) % candidate
U_i.set(U_temp)
U_i += V_temp
if U_i.is_odd():
U_i += candidate
U_i >>= 1
U_i %= candidate
# V_i = (((V_temp + U_temp * D) * K) >> 1) % candidate
V_i.set(V_temp)
V_i.multiply_accumulate(U_temp, D)
if V_i.is_odd():
V_i += candidate
V_i >>= 1
V_i %= candidate
else:
U_i.set(U_temp)
V_i.set(V_temp)
# Step 7
if U_i == 0:
return PROBABLY_PRIME
return COMPOSITE
from Crypto.Util.number import sieve_base as _sieve_base
## The optimal number of small primes to use for the sieve
## is probably dependent on the platform and the candidate size
_sieve_base = _sieve_base[:100]
def test_probable_prime(candidate, randfunc=None):
"""Test if a number is prime.
A number is qualified as prime if it passes a certain
number of Miller-Rabin tests (dependent on the size
of the number, but such that probability of a false
positive is less than 10^-30) and a single Lucas test.
For instance, a 1024-bit candidate will need to pass
4 Miller-Rabin tests.
:Parameters:
candidate : integer
The number to test for primality.
randfunc : callable
The routine to draw random bytes from to select Miller-Rabin bases.
:Returns:
``PROBABLE_PRIME`` if the number if prime with very high probability.
``COMPOSITE`` if the number is a composite.
For efficiency reasons, ``COMPOSITE`` is also returned for small primes.
"""
if randfunc is None:
randfunc = Random.new().read
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
# First, check trial division by the smallest primes
try:
list(map(candidate.fail_if_divisible_by, _sieve_base))
except ValueError:
return False
# These are the number of Miller-Rabin iterations s.t. p(k, t) < 1E-30,
# with p(k, t) being the probability that a randomly chosen k-bit number
# is composite but still survives t MR iterations.
mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10),
(620, 7), (740, 6), (890, 5), (1200, 4),
(1700, 3), (3700, 2))
bit_size = candidate.size_in_bits()
try:
mr_iterations = list([x for x in mr_ranges if bit_size < x[0]])[0][1]
except IndexError:
mr_iterations = 1
if miller_rabin_test(candidate, mr_iterations,
randfunc=randfunc) == COMPOSITE:
return COMPOSITE
if lucas_test(candidate) == COMPOSITE:
return COMPOSITE
return PROBABLY_PRIME
def generate_probable_prime(**kwargs):
"""Generate a random probable prime.
The prime will not have any specific properties
(e.g. it will not be a *strong* prime).
Random numbers are evaluated for primality until one
passes all tests, consisting of a certain number of
Miller-Rabin tests with random bases followed by
a single Lucas test.
The number of Miller-Rabin iterations is chosen such that
the probability that the output number is a non-prime is
less than 1E-30 (roughly 2^{-100}).
This approach is compliant to `FIPS PUB 186-4`__.
:Keywords:
exact_bits : integer
The desired size in bits of the probable prime.
It must be at least 160.
randfunc : callable
An RNG function where candidate primes are taken from.
prime_filter : callable
A function that takes an Integer as parameter and returns
True if the number can be passed to further primality tests,
False if it should be immediately discarded.
:Return:
A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1).
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
exact_bits = kwargs.pop("exact_bits", None)
randfunc = kwargs.pop("randfunc", None)
prime_filter = kwargs.pop("prime_filter", lambda x: True)
if kwargs:
print("Unknown parameters:", list(kwargs.keys()))
if exact_bits is None:
raise ValueError("Missing exact_bits parameter")
if exact_bits < 160:
raise ValueError("Prime number is not big enough.")
if randfunc is None:
randfunc = Random.new().read
result = COMPOSITE
while result == COMPOSITE:
candidate = Integer.random(exact_bits=exact_bits,
randfunc=randfunc) | 1
if not prime_filter(candidate):
continue
result = test_probable_prime(candidate, randfunc)
return candidate
def generate_probable_safe_prime(**kwargs):
"""Generate a random, probable safe prime.
Note this operation is much slower than generating a simple prime.
:Keywords:
exact_bits : integer
The desired size in bits of the probable safe prime.
randfunc : callable
An RNG function where candidate primes are taken from.
:Return:
A probable safe prime in the range
2^exact_bits > p > 2^(exact_bits-1).
"""
exact_bits = kwargs.pop("exact_bits", None)
randfunc = kwargs.pop("randfunc", None)
if kwargs:
print("Unknown parameters:", list(kwargs.keys()))
if randfunc is None:
randfunc = Random.new().read
result = COMPOSITE
while result == COMPOSITE:
q = generate_probable_prime(exact_bits=exact_bits - 1, randfunc=randfunc)
candidate = q * 2 + 1
if candidate.size_in_bits() != exact_bits:
continue
result = test_probable_prime(candidate, randfunc=randfunc)
return candidate

View file

@ -0,0 +1,720 @@
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
from Crypto.Util.py3compat import tobytes, b, bchr
from Crypto.Util._raw_api import (backend, load_lib,
get_raw_buffer, get_c_string,
null_pointer, create_string_buffer,
c_ulong, c_ulonglong, c_size_t)
# GMP uses unsigned longs in several functions prototypes.
# On a UNIX 64 bit platform that type takes 64 bits but in Windows 64
# it is still 32 bits.
# The intention of the MPIR developers is to maintain binary compatibility
# so they probably assumed that that GMP would compile on Windows 64
# by treating it as a UNIX platform.
gmp_defs_common = """
typedef struct { int a; int b; void *c; } MPZ;
typedef MPZ mpz_t[1];
typedef UNIX_ULONG mp_bitcnt_t;
void __gmpz_init (mpz_t x);
void __gmpz_init_set (mpz_t rop, const mpz_t op);
void __gmpz_init_set_ui (mpz_t rop, UNIX_ULONG op);
int __gmp_sscanf (const char *s, const char *fmt, ...);
void __gmpz_set (mpz_t rop, const mpz_t op);
int __gmp_snprintf (char *buf, size_t size, const char *fmt, ...);
void __gmpz_add (mpz_t rop, const mpz_t op1, const mpz_t op2);
void __gmpz_add_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
void __gmpz_sub_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
void __gmpz_addmul (mpz_t rop, const mpz_t op1, const mpz_t op2);
void __gmpz_addmul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
void __gmpz_submul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
void __gmpz_import (mpz_t rop, size_t count, int order, size_t size,
int endian, size_t nails, const void *op);
void * __gmpz_export (void *rop, size_t *countp, int order,
size_t size,
int endian, size_t nails, const mpz_t op);
size_t __gmpz_sizeinbase (const mpz_t op, int base);
void __gmpz_sub (mpz_t rop, const mpz_t op1, const mpz_t op2);
void __gmpz_mul (mpz_t rop, const mpz_t op1, const mpz_t op2);
void __gmpz_mul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
int __gmpz_cmp (const mpz_t op1, const mpz_t op2);
void __gmpz_powm (mpz_t rop, const mpz_t base, const mpz_t exp, const
mpz_t mod);
void __gmpz_powm_ui (mpz_t rop, const mpz_t base, UNIX_ULONG exp,
const mpz_t mod);
void __gmpz_pow_ui (mpz_t rop, const mpz_t base, UNIX_ULONG exp);
void __gmpz_sqrt(mpz_t rop, const mpz_t op);
void __gmpz_mod (mpz_t r, const mpz_t n, const mpz_t d);
void __gmpz_neg (mpz_t rop, const mpz_t op);
void __gmpz_abs (mpz_t rop, const mpz_t op);
void __gmpz_and (mpz_t rop, const mpz_t op1, const mpz_t op2);
void __gmpz_ior (mpz_t rop, const mpz_t op1, const mpz_t op2);
void __gmpz_clear (mpz_t x);
void __gmpz_tdiv_q_2exp (mpz_t q, const mpz_t n, mp_bitcnt_t b);
void __gmpz_fdiv_q (mpz_t q, const mpz_t n, const mpz_t d);
void __gmpz_mul_2exp (mpz_t rop, const mpz_t op1, mp_bitcnt_t op2);
int __gmpz_tstbit (const mpz_t op, mp_bitcnt_t bit_index);
int __gmpz_perfect_square_p (const mpz_t op);
int __gmpz_jacobi (const mpz_t a, const mpz_t b);
void __gmpz_gcd (mpz_t rop, const mpz_t op1, const mpz_t op2);
UNIX_ULONG __gmpz_gcd_ui (mpz_t rop, const mpz_t op1,
UNIX_ULONG op2);
void __gmpz_lcm (mpz_t rop, const mpz_t op1, const mpz_t op2);
int __gmpz_invert (mpz_t rop, const mpz_t op1, const mpz_t op2);
int __gmpz_divisible_p (const mpz_t n, const mpz_t d);
int __gmpz_divisible_ui_p (const mpz_t n, UNIX_ULONG d);
"""
try:
gmp_defs = "typedef unsigned long UNIX_ULONG;" + gmp_defs_common
lib = load_lib("gmp", gmp_defs)
implementation = { "library":"gmp", "api":backend }
except OSError:
import platform
bits, linkage = platform.architecture()
if bits.startswith("64") and linkage.startswith("Win"):
# MPIR uses unsigned long long where GMP uses unsigned long
# (LLP64 vs LP64)
gmp_defs = "typedef unsigned long long UNIX_ULONG;" + gmp_defs_common
c_ulong = c_ulonglong
# Try to load private MPIR lib first (wheel)
try:
from Crypto.Util._file_system import pycryptodome_filename
mpir_dll = pycryptodome_filename(("Crypto", "Math"), "mpir.dll")
lib = load_lib(mpir_dll, gmp_defs)
except OSError:
lib = load_lib("mpir", gmp_defs)
implementation = { "library":"mpir", "api":backend }
# In order to create a function that returns a pointer to
# a new MPZ structure, we need to break the abstraction
# and know exactly what ffi backend we have
if implementation["api"] == "ctypes":
from ctypes import Structure, c_int, c_void_p, byref
class _MPZ(Structure):
_fields_ = [('_mp_alloc', c_int),
('_mp_size', c_int),
('_mp_d', c_void_p)]
def new_mpz():
return byref(_MPZ())
else:
# We are using CFFI
from Crypto.Util._raw_api import ffi
def new_mpz():
return ffi.new("MPZ*")
# Unfortunately, all symbols exported by the GMP library start with "__"
# and have no trailing underscore.
# You cannot directly refer to them as members of the ctypes' library
# object from within any class because Python will replace the double
# underscore with "_classname_".
class _GMP(object):
pass
_gmp = _GMP()
_gmp = _GMP()
_gmp.mpz_init = lib.__gmpz_init
_gmp.mpz_init_set = lib.__gmpz_init_set
_gmp.mpz_init_set_ui = lib.__gmpz_init_set_ui
_gmp.mpz_set = lib.__gmpz_set
_gmp.gmp_snprintf = lib.__gmp_snprintf
_gmp.gmp_sscanf = lib.__gmp_sscanf
_gmp.mpz_add = lib.__gmpz_add
_gmp.mpz_add_ui = lib.__gmpz_add_ui
_gmp.mpz_sub_ui = lib.__gmpz_sub_ui
_gmp.mpz_addmul = lib.__gmpz_addmul
_gmp.mpz_addmul_ui = lib.__gmpz_addmul_ui
_gmp.mpz_submul_ui = lib.__gmpz_submul_ui
_gmp.mpz_import = lib.__gmpz_import
_gmp.mpz_export = lib.__gmpz_export
_gmp.mpz_sizeinbase = lib.__gmpz_sizeinbase
_gmp.mpz_sub = lib.__gmpz_sub
_gmp.mpz_mul = lib.__gmpz_mul
_gmp.mpz_mul_ui = lib.__gmpz_mul_ui
_gmp.mpz_cmp = lib.__gmpz_cmp
_gmp.mpz_powm = lib.__gmpz_powm
_gmp.mpz_powm_ui = lib.__gmpz_powm_ui
_gmp.mpz_pow_ui = lib.__gmpz_pow_ui
_gmp.mpz_sqrt = lib.__gmpz_sqrt
_gmp.mpz_mod = lib.__gmpz_mod
_gmp.mpz_neg = lib.__gmpz_neg
_gmp.mpz_abs = lib.__gmpz_abs
_gmp.mpz_and = lib.__gmpz_and
_gmp.mpz_ior = lib.__gmpz_ior
_gmp.mpz_clear = lib.__gmpz_clear
_gmp.mpz_tdiv_q_2exp = lib.__gmpz_tdiv_q_2exp
_gmp.mpz_fdiv_q = lib.__gmpz_fdiv_q
_gmp.mpz_mul_2exp = lib.__gmpz_mul_2exp
_gmp.mpz_tstbit = lib.__gmpz_tstbit
_gmp.mpz_perfect_square_p = lib.__gmpz_perfect_square_p
_gmp.mpz_jacobi = lib.__gmpz_jacobi
_gmp.mpz_gcd = lib.__gmpz_gcd
_gmp.mpz_gcd_ui = lib.__gmpz_gcd_ui
_gmp.mpz_lcm = lib.__gmpz_lcm
_gmp.mpz_invert = lib.__gmpz_invert
_gmp.mpz_divisible_p = lib.__gmpz_divisible_p
_gmp.mpz_divisible_ui_p = lib.__gmpz_divisible_ui_p
class Integer(object):
"""A fast, arbitrary precision integer"""
_zero_mpz_p = new_mpz()
_gmp.mpz_init_set_ui(_zero_mpz_p, c_ulong(0))
def __init__(self, value):
"""Initialize the integer to the given value."""
self._mpz_p = new_mpz()
self._initialized = False
if isinstance(value, float):
raise ValueError("A floating point type is not a natural number")
self._initialized = True
if isinstance(value, int):
_gmp.mpz_init(self._mpz_p)
result = _gmp.gmp_sscanf(tobytes(str(value)), b("%Zd"), self._mpz_p)
if result != 1:
raise ValueError("Error converting '%d'" % value)
else:
_gmp.mpz_init_set(self._mpz_p, value._mpz_p)
# Conversions
def __int__(self):
# buf will contain the integer encoded in decimal plus the trailing
# zero, and possibly the negative sign.
# dig10(x) < log10(x) + 1 = log2(x)/log2(10) + 1 < log2(x)/3 + 1
buf_len = _gmp.mpz_sizeinbase(self._mpz_p, 2) // 3 + 3
buf = create_string_buffer(buf_len)
_gmp.gmp_snprintf(buf, c_size_t(buf_len), b("%Zd"), self._mpz_p)
return int(get_c_string(buf))
def __str__(self):
return str(int(self))
def __repr__(self):
return "Integer(%s)" % str(self)
def to_bytes(self, block_size=0):
"""Convert the number into a byte string.
This method encodes the number in network order and prepends
as many zero bytes as required. It only works for non-negative
values.
:Parameters:
block_size : integer
The exact size the output byte string must have.
If zero, the string has the minimal length.
:Returns:
A byte string.
:Raise ValueError:
If the value is negative or if ``block_size`` is
provided and the length of the byte string would exceed it.
"""
if self < 0:
raise ValueError("Conversion only valid for non-negative numbers")
buf_len = (_gmp.mpz_sizeinbase(self._mpz_p, 2) + 7) // 8
if buf_len > block_size > 0:
raise ValueError("Number is too big to convert to byte string"
"of prescribed length")
buf = create_string_buffer(buf_len)
_gmp.mpz_export(
buf,
null_pointer, # Ignore countp
1, # Big endian
c_size_t(1), # Each word is 1 byte long
0, # Endianess within a word - not relevant
c_size_t(0), # No nails
self._mpz_p)
return bchr(0) * max(0, block_size - buf_len) + get_raw_buffer(buf)
@staticmethod
def from_bytes(byte_string):
"""Convert a byte string into a number.
:Parameters:
byte_string : byte string
The input number, encoded in network order.
It can only be non-negative.
:Return:
The ``Integer`` object carrying the same value as the input.
"""
result = Integer(0)
_gmp.mpz_import(
result._mpz_p,
c_size_t(len(byte_string)), # Amount of words to read
1, # Big endian
c_size_t(1), # Each word is 1 byte long
0, # Endianess within a word - not relevant
c_size_t(0), # No nails
byte_string)
return result
# Relations
def _apply_and_return(self, func, term):
if not isinstance(term, Integer):
term = Integer(term)
return func(self._mpz_p, term._mpz_p)
def __eq__(self, term):
if not isinstance(term, (Integer, int)):
return False
return self._apply_and_return(_gmp.mpz_cmp, term) == 0
def __ne__(self, term):
if not isinstance(term, (Integer, int)):
return True
return self._apply_and_return(_gmp.mpz_cmp, term) != 0
def __lt__(self, term):
return self._apply_and_return(_gmp.mpz_cmp, term) < 0
def __le__(self, term):
return self._apply_and_return(_gmp.mpz_cmp, term) <= 0
def __gt__(self, term):
return self._apply_and_return(_gmp.mpz_cmp, term) > 0
def __ge__(self, term):
return self._apply_and_return(_gmp.mpz_cmp, term) >= 0
def __bool__(self):
return _gmp.mpz_cmp(self._mpz_p, self._zero_mpz_p) != 0
def is_negative(self):
return _gmp.mpz_cmp(self._mpz_p, self._zero_mpz_p) < 0
# Arithmetic operations
def __add__(self, term):
result = Integer(0)
if not isinstance(term, Integer):
term = Integer(term)
_gmp.mpz_add(result._mpz_p,
self._mpz_p,
term._mpz_p)
return result
def __sub__(self, term):
result = Integer(0)
if not isinstance(term, Integer):
term = Integer(term)
_gmp.mpz_sub(result._mpz_p,
self._mpz_p,
term._mpz_p)
return result
def __mul__(self, term):
result = Integer(0)
if not isinstance(term, Integer):
term = Integer(term)
_gmp.mpz_mul(result._mpz_p,
self._mpz_p,
term._mpz_p)
return result
def __floordiv__(self, divisor):
if not isinstance(divisor, Integer):
divisor = Integer(divisor)
if _gmp.mpz_cmp(divisor._mpz_p,
self._zero_mpz_p) == 0:
raise ZeroDivisionError("Division by zero")
result = Integer(0)
_gmp.mpz_fdiv_q(result._mpz_p,
self._mpz_p,
divisor._mpz_p)
return result
def __mod__(self, divisor):
if not isinstance(divisor, Integer):
divisor = Integer(divisor)
comp = _gmp.mpz_cmp(divisor._mpz_p,
self._zero_mpz_p)
if comp == 0:
raise ZeroDivisionError("Division by zero")
if comp < 0:
raise ValueError("Modulus must be positive")
result = Integer(0)
_gmp.mpz_mod(result._mpz_p,
self._mpz_p,
divisor._mpz_p)
return result
def inplace_pow(self, exponent, modulus=None):
if modulus is None:
if exponent < 0:
raise ValueError("Exponent must not be negative")
# Normal exponentiation
if exponent > 256:
raise ValueError("Exponent is too big")
_gmp.mpz_pow_ui(self._mpz_p,
self._mpz_p, # Base
c_ulong(int(exponent))
)
else:
# Modular exponentiation
if not isinstance(modulus, Integer):
modulus = Integer(modulus)
if not modulus:
raise ZeroDivisionError("Division by zero")
if modulus.is_negative():
raise ValueError("Modulus must be positive")
if isinstance(exponent, int):
if exponent < 0:
raise ValueError("Exponent must not be negative")
if exponent < 65536:
_gmp.mpz_powm_ui(self._mpz_p,
self._mpz_p,
c_ulong(exponent),
modulus._mpz_p)
return self
exponent = Integer(exponent)
elif exponent.is_negative():
raise ValueError("Exponent must not be negative")
_gmp.mpz_powm(self._mpz_p,
self._mpz_p,
exponent._mpz_p,
modulus._mpz_p)
return self
def __pow__(self, exponent, modulus=None):
result = Integer(self)
return result.inplace_pow(exponent, modulus)
def __abs__(self):
result = Integer(0)
_gmp.mpz_abs(result._mpz_p, self._mpz_p)
return result
def sqrt(self):
"""Return the largest Integer that does not
exceed the square root"""
if self < 0:
raise ValueError("Square root of negative value")
result = Integer(0)
_gmp.mpz_sqrt(result._mpz_p,
self._mpz_p)
return result
def __iadd__(self, term):
if isinstance(term, int):
if 0 <= term < 65536:
_gmp.mpz_add_ui(self._mpz_p,
self._mpz_p,
c_ulong(term))
return self
if -65535 < term < 0:
_gmp.mpz_sub_ui(self._mpz_p,
self._mpz_p,
c_ulong(-term))
return self
term = Integer(term)
_gmp.mpz_add(self._mpz_p,
self._mpz_p,
term._mpz_p)
return self
def __isub__(self, term):
if isinstance(term, int):
if 0 <= term < 65536:
_gmp.mpz_sub_ui(self._mpz_p,
self._mpz_p,
c_ulong(term))
return self
if -65535 < term < 0:
_gmp.mpz_add_ui(self._mpz_p,
self._mpz_p,
c_ulong(-term))
return self
term = Integer(term)
_gmp.mpz_sub(self._mpz_p,
self._mpz_p,
term._mpz_p)
return self
def __imul__(self, term):
if isinstance(term, int):
if 0 <= term < 65536:
_gmp.mpz_mul_ui(self._mpz_p,
self._mpz_p,
c_ulong(term))
return self
if -65535 < term < 0:
_gmp.mpz_mul_ui(self._mpz_p,
self._mpz_p,
c_ulong(-term))
_gmp.mpz_neg(self._mpz_p, self._mpz_p)
return self
term = Integer(term)
_gmp.mpz_mul(self._mpz_p,
self._mpz_p,
term._mpz_p)
return self
def __imod__(self, divisor):
if not isinstance(divisor, Integer):
divisor = Integer(divisor)
comp = _gmp.mpz_cmp(divisor._mpz_p,
divisor._zero_mpz_p)
if comp == 0:
raise ZeroDivisionError("Division by zero")
if comp < 0:
raise ValueError("Modulus must be positive")
_gmp.mpz_mod(self._mpz_p,
self._mpz_p,
divisor._mpz_p)
return self
# Boolean/bit operations
def __and__(self, term):
result = Integer(0)
if not isinstance(term, Integer):
term = Integer(term)
_gmp.mpz_and(result._mpz_p,
self._mpz_p,
term._mpz_p)
return result
def __or__(self, term):
result = Integer(0)
if not isinstance(term, Integer):
term = Integer(term)
_gmp.mpz_ior(result._mpz_p,
self._mpz_p,
term._mpz_p)
return result
def __rshift__(self, pos):
result = Integer(0)
if not 0 <= pos < 65536:
raise ValueError("Incorrect shift count")
_gmp.mpz_tdiv_q_2exp(result._mpz_p,
self._mpz_p,
c_ulong(int(pos)))
return result
def __irshift__(self, pos):
if not 0 <= pos < 65536:
raise ValueError("Incorrect shift count")
_gmp.mpz_tdiv_q_2exp(self._mpz_p,
self._mpz_p,
c_ulong(int(pos)))
return self
def __lshift__(self, pos):
result = Integer(0)
if not 0 <= pos < 65536:
raise ValueError("Incorrect shift count")
_gmp.mpz_mul_2exp(result._mpz_p,
self._mpz_p,
c_ulong(int(pos)))
return result
def __ilshift__(self, pos):
if not 0 <= pos < 65536:
raise ValueError("Incorrect shift count")
_gmp.mpz_mul_2exp(self._mpz_p,
self._mpz_p,
c_ulong(int(pos)))
return self
def get_bit(self, n):
"""Return True if the n-th bit is set to 1.
Bit 0 is the least significant."""
if not 0 <= n < 65536:
raise ValueError("Incorrect bit position")
return bool(_gmp.mpz_tstbit(self._mpz_p,
c_ulong(int(n))))
# Extra
def is_odd(self):
return _gmp.mpz_tstbit(self._mpz_p, 0) == 1
def is_even(self):
return _gmp.mpz_tstbit(self._mpz_p, 0) == 0
def size_in_bits(self):
"""Return the minimum number of bits that can encode the number."""
if self < 0:
raise ValueError("Conversion only valid for non-negative numbers")
return _gmp.mpz_sizeinbase(self._mpz_p, 2)
def size_in_bytes(self):
"""Return the minimum number of bytes that can encode the number."""
return (self.size_in_bits() - 1) // 8 + 1
def is_perfect_square(self):
return _gmp.mpz_perfect_square_p(self._mpz_p) != 0
def fail_if_divisible_by(self, small_prime):
"""Raise an exception if the small prime is a divisor."""
if isinstance(small_prime, int):
if 0 < small_prime < 65536:
if _gmp.mpz_divisible_ui_p(self._mpz_p,
c_ulong(small_prime)):
raise ValueError("The value is composite")
return
small_prime = Integer(small_prime)
if _gmp.mpz_divisible_p(self._mpz_p,
small_prime._mpz_p):
raise ValueError("The value is composite")
def multiply_accumulate(self, a, b):
"""Increment the number by the product of a and b."""
if not isinstance(a, Integer):
a = Integer(a)
if isinstance(b, int):
if 0 < b < 65536:
_gmp.mpz_addmul_ui(self._mpz_p,
a._mpz_p,
c_ulong(b))
return self
if -65535 < b < 0:
_gmp.mpz_submul_ui(self._mpz_p,
a._mpz_p,
c_ulong(-b))
return self
b = Integer(b)
_gmp.mpz_addmul(self._mpz_p,
a._mpz_p,
b._mpz_p)
return self
def set(self, source):
"""Set the Integer to have the given value"""
if not isinstance(source, Integer):
source = Integer(source)
_gmp.mpz_set(self._mpz_p,
source._mpz_p)
return self
def inplace_inverse(self, modulus):
"""Compute the inverse of this number in the ring of
modulo integers.
Raise an exception if no inverse exists.
"""
if not isinstance(modulus, Integer):
modulus = Integer(modulus)
comp = _gmp.mpz_cmp(modulus._mpz_p,
self._zero_mpz_p)
if comp == 0:
raise ZeroDivisionError("Modulus cannot be zero")
if comp < 0:
raise ValueError("Modulus must be positive")
result = _gmp.mpz_invert(self._mpz_p,
self._mpz_p,
modulus._mpz_p)
if not result:
raise ValueError("No inverse value can be computed")
return self
def inverse(self, modulus):
result = Integer(self)
result.inplace_inverse(modulus)
return result
def gcd(self, term):
"""Compute the greatest common denominator between this
number and another term."""
result = Integer(0)
if isinstance(term, int):
if 0 < term < 65535:
_gmp.mpz_gcd_ui(result._mpz_p,
self._mpz_p,
c_ulong(term))
return result
term = Integer(term)
_gmp.mpz_gcd(result._mpz_p, self._mpz_p, term._mpz_p)
return result
def lcm(self, term):
"""Compute the least common multiplier between this
number and another term."""
result = Integer(0)
if not isinstance(term, Integer):
term = Integer(term)
_gmp.mpz_lcm(result._mpz_p, self._mpz_p, term._mpz_p)
return result
@staticmethod
def jacobi_symbol(a, n):
"""Compute the Jacobi symbol"""
if not isinstance(a, Integer):
a = Integer(a)
if not isinstance(n, Integer):
n = Integer(n)
if n <= 0 or n.is_even():
raise ValueError("n must be positive even for the Jacobi symbol")
return _gmp.mpz_jacobi(a._mpz_p, n._mpz_p)
# Clean-up
def __del__(self):
try:
if self._mpz_p is not None:
if self._initialized:
_gmp.mpz_clear(self._mpz_p)
self._mpz_p = None
except AttributeError:
pass

View file

@ -0,0 +1,415 @@
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
from Crypto.Util.number import long_to_bytes, bytes_to_long
from Crypto.Util.py3compat import maxint
class Integer(object):
"""A class to model a natural integer (including zero)"""
def __init__(self, value):
if isinstance(value, float):
raise ValueError("A floating point type is not a natural number")
try:
self._value = value._value
except AttributeError:
self._value = value
# Conversions
def __int__(self):
return self._value
def __str__(self):
return str(int(self))
def __repr__(self):
return "Integer(%s)" % str(self)
def to_bytes(self, block_size=0):
if self._value < 0:
raise ValueError("Conversion only valid for non-negative numbers")
result = long_to_bytes(self._value, block_size)
if len(result) > block_size > 0:
raise ValueError("Value too large to encode")
return result
@staticmethod
def from_bytes(byte_string):
return Integer(bytes_to_long(byte_string))
# Relations
def __eq__(self, term):
try:
result = self._value == term._value
except AttributeError:
result = self._value == term
return result
def __ne__(self, term):
return not self.__eq__(term)
def __lt__(self, term):
try:
result = self._value < term._value
except AttributeError:
result = self._value < term
return result
def __le__(self, term):
return self.__lt__(term) or self.__eq__(term)
def __gt__(self, term):
return not self.__le__(term)
def __ge__(self, term):
return not self.__lt__(term)
def __bool__(self):
return self._value != 0
def is_negative(self):
return self._value < 0
# Arithmetic operations
def __add__(self, term):
try:
return Integer(self._value + term._value)
except AttributeError:
return Integer(self._value + term)
def __sub__(self, term):
try:
diff = self._value - term._value
except AttributeError:
diff = self._value - term
return Integer(diff)
def __mul__(self, factor):
try:
return Integer(self._value * factor._value)
except AttributeError:
return Integer(self._value * factor)
def __floordiv__(self, divisor):
try:
divisor_value = divisor._value
except AttributeError:
divisor_value = divisor
return Integer(self._value // divisor_value)
def __mod__(self, divisor):
try:
divisor_value = divisor._value
except AttributeError:
divisor_value = divisor
if divisor_value < 0:
raise ValueError("Modulus must be positive")
return Integer(self._value % divisor_value)
def inplace_pow(self, exponent, modulus=None):
try:
exp_value = exponent._value
except AttributeError:
exp_value = exponent
if exp_value < 0:
raise ValueError("Exponent must not be negative")
try:
mod_value = modulus._value
except AttributeError:
mod_value = modulus
if mod_value is not None:
if mod_value < 0:
raise ValueError("Modulus must be positive")
if mod_value == 0:
raise ZeroDivisionError("Modulus cannot be zero")
self._value = pow(self._value, exp_value, mod_value)
return self
def __pow__(self, exponent, modulus=None):
result = Integer(self)
return result.inplace_pow(exponent, modulus)
def __abs__(self):
return abs(self._value)
def sqrt(self):
# http://stackoverflow.com/questions/15390807/integer-square-root-in-python
if self._value < 0:
raise ValueError("Square root of negative value")
x = self._value
y = (x + 1) // 2
while y < x:
x = y
y = (x + self._value // x) // 2
return Integer(x)
def __iadd__(self, term):
try:
self._value += term._value
except AttributeError:
self._value += term
return self
def __isub__(self, term):
try:
self._value -= term._value
except AttributeError:
self._value -= term
return self
def __imul__(self, term):
try:
self._value *= term._value
except AttributeError:
self._value *= term
return self
def __imod__(self, term):
try:
modulus = term._value
except AttributeError:
modulus = term
if modulus == 0:
raise ZeroDivisionError("Division by zero")
if modulus < 0:
raise ValueError("Modulus must be positive")
self._value %= modulus
return self
# Boolean/bit operations
def __and__(self, term):
try:
return Integer(self._value & term._value)
except AttributeError:
return Integer(self._value & term)
def __or__(self, term):
try:
return Integer(self._value | term._value)
except AttributeError:
return Integer(self._value | term)
def __rshift__(self, pos):
try:
try:
return Integer(self._value >> pos._value)
except AttributeError:
return Integer(self._value >> pos)
except OverflowError:
raise ValueError("Incorrect shift count")
def __irshift__(self, pos):
try:
try:
self._value >>= pos._value
except AttributeError:
self._value >>= pos
except OverflowError:
raise ValueError("Incorrect shift count")
return self
def __lshift__(self, pos):
try:
try:
return Integer(self._value << pos._value)
except AttributeError:
return Integer(self._value << pos)
except OverflowError:
raise ValueError("Incorrect shift count")
def __ilshift__(self, pos):
try:
try:
self._value <<= pos._value
except AttributeError:
self._value <<= pos
except OverflowError:
raise ValueError("Incorrect shift count")
return self
def get_bit(self, n):
try:
try:
return (self._value >> n._value) & 1
except AttributeError:
return (self._value >> n) & 1
except OverflowError:
raise ValueError("Incorrect bit position")
# Extra
def is_odd(self):
return (self._value & 1) == 1
def is_even(self):
return (self._value & 1) == 0
def size_in_bits(self):
if self._value < 0:
raise ValueError("Conversion only valid for non-negative numbers")
if self._value == 0:
return 1
bit_size = 0
tmp = self._value
while tmp:
tmp >>= 1
bit_size += 1
return bit_size
def size_in_bytes(self):
return (self.size_in_bits() - 1) // 8 + 1
def is_perfect_square(self):
if self._value < 0:
return False
if self._value in (0, 1):
return True
x = self._value // 2
square_x = x ** 2
while square_x > self._value:
x = (square_x + self._value) // (2 * x)
square_x = x ** 2
return self._value == x ** 2
def fail_if_divisible_by(self, small_prime):
try:
if (self._value % small_prime._value) == 0:
raise ValueError("Value is composite")
except AttributeError:
if (self._value % small_prime) == 0:
raise ValueError("Value is composite")
def multiply_accumulate(self, a, b):
if type(a) == Integer:
a = a._value
if type(b) == Integer:
b = b._value
self._value += a * b
return self
def set(self, source):
if type(source) == Integer:
self._value = source._value
else:
self._value = source
def inplace_inverse(self, modulus):
try:
modulus = modulus._value
except AttributeError:
pass
if modulus == 0:
raise ZeroDivisionError("Modulus cannot be zero")
if modulus < 0:
raise ValueError("Modulus cannot be negative")
r_p, r_n = self._value, modulus
s_p, s_n = 1, 0
while r_n > 0:
q = r_p // r_n
r_p, r_n = r_n, r_p - q * r_n
s_p, s_n = s_n, s_p - q * s_n
if r_p != 1:
raise ValueError("No inverse value can be computed" + str(r_p))
while s_p < 0:
s_p += modulus
self._value = s_p
return self
def inverse(self, modulus):
result = Integer(self)
result.inplace_inverse(modulus)
return result
def gcd(self, term):
try:
term = term._value
except AttributeError:
pass
r_p, r_n = abs(self._value), abs(term)
while r_n > 0:
q = r_p // r_n
r_p, r_n = r_n, r_p - q * r_n
return Integer(r_p)
def lcm(self, term):
try:
term = term._value
except AttributeError:
pass
if self._value == 0 or term == 0:
return Integer(0)
return Integer(abs((self._value * term) // self.gcd(term)._value))
@staticmethod
def jacobi_symbol(a, n):
if isinstance(a, Integer):
a = a._value
if isinstance(n, Integer):
n = n._value
if (n & 1) == 0:
raise ValueError("n must be even for the Jacobi symbol")
# Step 1
a = a % n
# Step 2
if a == 1 or n == 1:
return 1
# Step 3
if a == 0:
return 0
# Step 4
e = 0
a1 = a
while (a1 & 1) == 0:
a1 >>= 1
e += 1
# Step 5
if (e & 1) == 0:
s = 1
elif n % 8 in (1, 7):
s = 1
else:
s = -1
# Step 6
if n % 4 == 3 and a1 % 4 == 3:
s = -s
# Step 7
n1 = n % a1
# Step 8
return s * Integer.jacobi_symbol(n1, a1)

View file

@ -0,0 +1,33 @@
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
"""
:undocumented: _Numbers_gmp, _Numbers_int
"""

Binary file not shown.