def greatest_n(phi_max): '''Finds the greatest n such that phi(n) < phi_max. Returns the greatest n such that phi(n) < phi_max.''' phi_product = 1 product = 1 prime = 1 while phi_product <= phi_max: prime = next_prime(prime) phi_product *= prime - 1 product *= prime n_max = (phi_max * product) // phi_product phi_values = list(range(n_max)) prime = 2 while prime <= n_max: for i in range(0, n_max, prime): phi_values[i] -= phi_values[i] // prime prime = next_prime(prime) for i in range(n_max - 1, 0, -1): if phi_values[i] <= phi_max: return i
def new_prime(): np = mpz(r.getrandbits(DH_Consts.bits - 1)) np = gmpy2.next_prime(np) while not gmpy2.is_prime(2 * np + 1, 25): np = gmpy2.next_prime(np) return mpz(2 * np + 1)
def generate_key(bitlength): temp = gmpy2.next_prime(2**bitlength) for i in range(x): temp = gmpy2.next_prime(temp) p = gmpy2.next_prime(temp) # look at this line q = gmpy2.next_prime(p) # and that!! return p,q
def generate_key(bitlength): temp = gmpy2.next_prime(2**bitlength) for i in range(x): temp = gmpy2.next_prime(temp) p = gmpy2.next_prime(temp) q = gmpy2.next_prime(p) return p,q
def keygen(size): rs = gmpy2.random_state(int(time.time())) p = gmpy2.next_prime(gmpy2.mpz_urandomb(rs, size)) while p % 4 != 3: p = gmpy2.next_prime(p) q = gmpy2.next_prime(p) while q % 4 != 3: q = gmpy2.next_prime(q) n = p*q x = n-1 return (x, n), (p, q)
def test_divisorGenerator(self): divisors_of_30 = [1, 2, 3, 5, 6, 10, 15, 30] self.assertEqual(eulertools.divisorGenerator(30),divisors_of_30) p= int( gmpy2.next_prime(97)) for _ in xrange(10): p = int (gmpy2.next_prime(p)) self.assertEqual([1,p] ,eulertools.divisorGenerator(p) ) try: eulertools.divisorGenerator('a') raise AssertionError('eulertools.divisorGenerator should raise exception for str input') except: pass
def break_keygen(n): start_val = 1475784906 while True: rs = gmpy2.random_state(start_val) p = gmpy2.next_prime(gmpy2.mpz_urandomb(rs, 2048)) while p % 4 != 3: p = gmpy2.next_prime(p) if n % p == 0: print p break start_val -= 1
def gen_keys(): rs = gmpy2.random_state(hash(gmpy2.random_state())) P = gmpy2.mpz_urandomb(rs, mpz('128')) P = gmpy2.next_prime(P) Q = gmpy2.mpz_urandomb(rs, mpz('128')) Q = gmpy2.next_prime(Q) N = P*Q Fi = (P-1)*(Q-1) Pkey = gmpy2.mpz_random(rs, Fi) while not (gmpy2.gcd(Fi, Pkey) == 1): Pkey = gmpy2.mpz_random(rs, Fi) Skey = gmpy2.invert(Pkey, Fi) assert gmpy2.t_mod(Skey*Pkey,Fi) == 1 return Pkey, Skey, N
def getprimeover(n): """return a random n-bit prime number """ r = gmpy2.mpz(random.SystemRandom().getrandbits(n)) r = gmpy2.bit_set(r, n - 1) return int(gmpy2.next_prime(r))
def get_root(index, p, k, c): # Find m such that m^index=c mod p^k # assert index < 1000 print("p = " + hex(p)) assert gmpy2.is_prime(p) assert p.bit_length() * k <= (2 << 16) n = p**k phi = (p**(k - 1)) * (p - 1) c %= n # First, split index into 2 parts, invert-able and un-invert-able. un_invert_able = gmpy2.gcd(index, phi) invert_able = index // un_invert_able while True: gcd = gmpy2.gcd(invert_able, phi) if gcd == 1: break invert_able //= gcd un_invert_able *= gcd assert invert_able * un_invert_able == index assert gmpy2.gcd(invert_able, phi) == 1 print(invert_able, un_invert_able) # Get rid of the invert-able part. d = gmpy2.invert(invert_able, phi) c2 = pow(c, d, n) assert pow(c2, invert_able, n) == c print("c2 = " + hex(c2)) # Next, find m such that m^un_invert_able=c2 mod p^k. Y = gmpy2.gcd(index, phi) X = phi // Y while True: gcd = gmpy2.gcd(X, un_invert_able) if gcd == 1: break X //= gcd Y *= gcd assert X * Y == phi assert gmpy2.gcd(un_invert_able + X, phi) == 1 print("X = 0x%x,\nY = %d" % (X, Y)) # Got a suitable Y. ans = set() counter = 0 while True: g = gmpy2.next_prime(getRandomInteger(p.bit_length()) % p) for i in range(Y): m_uninv_and_X = c2 * pow(g, i * phi // Y, n) % n assert pow(m_uninv_and_X, Y, n) == pow(c2, Y, n) m = pow(m_uninv_and_X, gmpy2.invert(un_invert_able + X, phi), n) if pow(m, un_invert_able, n) == c2: ans.add(m) counter += 1 if len(ans) >= un_invert_able or counter >= 10: break for m in ans: assert pow(m, index, n) == c return ans
def nth_prime(n): numberOfPrime = 1 result = 2 while (n > numberOfPrime): result = next_prime(result) numberOfPrime += 1 return int(result)
def could_be_prime(n): '''Performs some trials to compute whether n could be prime. Run time is O(N^3 / (log N)^2) for N bits. Returns whether it is possible for n to be prime (True or False). ''' if n < 2: return False if n == 2: return True if not n & 1: return False product = ONE log_n = int(math.log(n)) + 1 bound = int(math.log(n) / (LOG_2 * math.log(math.log(n))**2)) + 1 if bound * log_n >= n: bound = 1 log_n = int(sqrt(n)) prime_bound = 0 prime = 3 for _ in range(bound): p = [] prime_bound += log_n while prime <= prime_bound: p.append(prime) prime = next_prime(prime) if p != []: p = prod(p) product = (product * p) % n return gcd(n, product) == 1
def __init__(self, seed, s=2, k=150): self.k = k self.Y = next_prime(seed) self.M = 2**(60 * s) self.set = {} self.n = 0 self.set[self.n] = [self.Y**i for i in range(1, self.k + 1)]
def genPrime(nbit): while True: p = getPrime(512) if p % 9 == 1 and p % 27 >= 2: q = gmpy2.next_prime(serifin(p, 3) + serifin(p, 9) + serifin(p, 27)) if q % 9 == 1 and q % 27 >= 2: return int(p), int(q)
def primorial(r): p = 1 tmp = 1 for i in range(0, r): p = gmpy2.next_prime(p) tmp *= p return tmp
def attack(self, publickey, cipher=[]): """Run tests against primorial +-1 composites""" with timeout(self.timeout): try: limit = 10000 prime = 1 primorial = 1 p = q = None for x in tqdm(range(0, limit)): prime = next_prime(prime) primorial *= prime primorial_p1 = [primorial - 1, primorial + 1] g0, g1 = gcd(primorial_p1[0], publickey.n), gcd(primorial_p1[1], publickey.n) if 1 < g0 < publickey.n: p = publickey.n // g0 q = g0 break if 1 < g1 < publickey.n: p = publickey.n // g1 q = g1 break if p is not None and q is not None: priv_key = PrivateKey(int(p), int(q), int(publickey.e), int(publickey.n)) return (priv_key, None) return (None, None) except TimeoutError: return (None, None)
def could_be_prime(n): '''Performs some trials to compute whether n could be prime. Run time is O(N^3 / (log N)^2) for N bits. Returns whether it is possible for n to be prime (True or False). ''' if n < 2: return False if n == 2: return True if not int(n) & 1: return False product = ONE log_n = int(math.log(n)) + 1 bound = int(math.log(n) / (LOG_2 * math.log(math.log(n))**2)) + 1 if bound * log_n >= n: bound = 1 log_n = int(sqrt(n)) prime_bound = 0 prime = 3 for _ in range(bound): p = [] prime_bound += log_n while prime <= prime_bound: p.append(prime) prime = next_prime(prime) if p != []: p = prod(p) product = (product * p) % n return gcd(n, product) == 1
def factorize(x): r""" >>> factorize(a) [3, 41] >>> factorize(b) [2, 2, 2, 3, 19] >>> """ savex = x prime = 2 x = _g.mpz(x) factors = [] while x >= prime: newx, mult = _g.remove(x, prime) if mult: factors.extend([int(prime)] * mult) x = newx prime = _g.next_prime(prime) for factor in factors: assert _g.is_prime(factor) from operator import mul from functools import reduce assert reduce(mul, factors) == savex return factors
def p_q_gen(self, bits): self.p = mpz(2)**(bits - 1) + mpz_urandomb(rand, bits - 1) while True: self.p = next_prime(self.p) self.q = f_div(self.p - 1, 2) if is_prime(self.q): break
def angriff(param_root): ''' m1, m2 prime and <= b First creating dict with c_i = (c/m1^e) mod n as {c_i : m1} Then testing if any m2^e matches any c_i. If match: Test if (m1*m2)^e == C (mod n) -> yes: (m1*m2) = Message ''' _n, _e, _c, _b = read_parameters(param_root) # print("n = ", _n) # print("e = ", _e) # print("c = ", _c) # print("b = ", _b) candidates = {} prime_m1 = 2 prime_m2 = 2 match = False print("Calculating C_i ...") while prime_m1 <= _b: p_m1 = pow(prime_m1, _e, _n) c_i = _c * gmpy2.invert(p_m1, _n) c_i = c_i % _n candidates[c_i] = prime_m1 prime_m1 = gmpy2.next_prime(prime_m1) print("Searching for a match ...") while prime_m2 <= _b: p_m2 = pow(prime_m2, _e, _n) if p_m2 in candidates: m_1 = candidates[p_m2] m_2 = prime_m2 print("possible match... ") if test(m_1, m_2, _n, _e, _c): match = True break print("was not a match") prime_m2 = gmpy2.next_prime(prime_m2) if match: message = (m_1 * m_2) % _n print("The message is", message, "with m1 =", m_1, "and m2 =", m_2, ".") return message print("No match found") return None
def get_ways(num, minp=2): if num == 0: return 1 ways, p = 0, minp while p <= num: ways += get_ways(num - p, max(minp, p)) p = next_prime(p) return ways
def __init__(self, nv=5): #generate keys for PPKE and blindsign #generate primes p,q, such that p>q # and (p-1)*(q-1) is coprime with p*q p = gmpy2.next_prime(100000000) for _ in range(0, random.randint(0, 300000)): p = gmpy2.next_prime(p) q = p for _ in range(0, random.randint(1, 100000)): p = gmpy2.next_prime(p) n = p * q while fractions.gcd((q - 1) * (p - 1), n) != 1: q = gmpy2.next_prime(q) n = p * q n2 = n**2 # n^2 to be used for modulus lam = ((p - 1) * (q - 1)) be = random.randint(1, lam) bd = modinv(be, lam) while 1 != fractions.gcd(be, lam) or bd is None: be = random.randint(1, lam) bd = modinv(be, lam) lam = lam / fractions.gcd(p - 1, q - 1) # least common multiple u = None g = None while u is None: g = n2 while 1 != fractions.gcd(g, n2): a = random.randint(1, n) b = random.randint(1, n) g = ((a * n + 1) * pow(b, n, n2)) % n2 #ensure u and n are coprime u = (pow(g, lam, n2) - 1) // n if (fractions.gcd(u, n)) != 1: print "This shouldn't happen" u = None else: u = modinv(u, n) self.n = n self.p = p self.q = q self.lam = lam self.g = g self.u = u self.be = be self.bd = bd self.numvoters = nv
def genE(lcm, limit): while True: r = random.randint(limit, limit * 0x1000000000001) d = gmpy2.next_prime(r) e = gmpy2.invert(d, lcm) if isPrime(e): break return e
def generate_prime(bit_length): left = 2**(bit_length - 1) right = 2**bit_length - 1 while True: random_integer = random.randint(left, right) random_prime = gmpy2.next_prime(random_integer) if random_prime <= right: return random_prime
def generate_keys(): # prime number of 25 digits i.e 84 bits temp = 1000000000000000000000000 random_add1 = np.random.randint(1, 1000000) random_add2 = np.random.randint(1000000, 2000000) p = int(gmpy2.next_prime(temp + random_add1)) q = int(gmpy2.next_prime(temp + random_add2)) n = p * q phi = (p - 1) * (q - 1) e = 2 while True: if gmpy2.gcd(phi, e) != 1: e = e + 1 else: break d = gmpy2.invert(e, phi) return n, e, d
def prime_number(lowerBound, upperBound): ''' Модуль для генерации "большого" простого числа в пределах. ''' random_number = random.randint(lowerBound, upperBound) random_prime_number = gmpy2.next_prime(random_number) return random_prime_number
def gen_key(size): b = gen_inc_list(size) q = b[-1] for i in range(rand(BUF // 2)): q = int(next_prime(q << 1)) r = b[-1] + rand(BUF << 3) pb = [(r * i) % q for i in b] return (b, r, q), pb
def genlist(start, l): result = [] while len(result) != l: start = next_prime(start) temp = str(start) if temp == temp[::-1]: result.append(start) return result
def find_primes(target): nextprime = target while True: nextprime = gmpy2.next_prime(nextprime) if gmpy2.is_prime(nextprime-target): print "Found", hex(nextprime), hex(nextprime-target) return nextprime, nextprime-target break
def random_prime(size): seed = int.from_bytes(os.urandom(16), byteorder='little') state = gmpy2.random_state(seed) rnd = gmpy2.mpz_rrandomb(state, size) while True: prime = gmpy2.next_prime(rnd) if prime.bit_length() == size: return prime
def generate_random_prime(prime_index_range_start, prime_index_range_end): p = prime_index_range_start lista = [] for i in range(prime_index_range_end - prime_index_range_start): p = gmpy2.next_prime(p) lista.append(p) return lista
def __init__(self, name): self.point_name = name self.network_key = 'shaobao123' self.MAC = random_hex(6) self.private_key = gmp.next_prime(random_hex(128)) self.SESSIONID = None self.content = 'hello console! I am point {}'.format(name)
def factors(n, veb, ra, ov, pr): '''Generates factors of n. Strips small primes, then feeds to ecm function. Input: n -- An integer to factor veb -- If True, be verbose ra -- If True, select sigma values randomly ov -- How asymptotically fast the calculation is pr -- What portion of the total processing power this run gets Output: Factors of n, via a generator. Notes: 1. A good value of ov for typical numbers is somewhere around 10. If this parameter is too high, overhead and memory usage grow. 2. If ra is set to False and veb is set to True, then results are reproducible. If ra is set to True, then one number may be done in parallel on disconnected machines (at only a small loss of efficiency, which is less if pr is set correctly).''' if type(n) not in T: raise ValueError('Number given must be integer or long.') if not 0 < pr <= 1: yield 'Error: pr must be between 0 and 1' return while not n & 1: n >>= 1 yield 2 n = mpz(n) k = inv_const(n) prime = 2 trial_division_bound = max(10 * k**2, 100) while prime < trial_division_bound: prime = next_prime(prime) while not n % prime: n = n // prime yield prime if n in g.factorCache: if veb and n != 1: print( 'cache hit:', n ) for i in getExpandedFactorList( g.factorCache[ n ] ): yield i return if isprime(n): yield n return if n == 1: return for factor in ecm(n, ra, ov, veb, trial_division_bound, pr): yield factor
def make_prime_list(): prime_list = [] power_list = [] b = 1 while b <= B: b = next_prime(b) prime_list.append(b) power_list.append(int(log(B) / log(b))) return prime_list, power_list
def update_score(self, login, result, new_task): cur = yield self.POOL.execute(self.LOGIN, (login, )) res = cur.fetchall()[0] new_balance, task = res[2:] if next_prime(task) == result: new_balance += 1 yield self.POOL.execute(self.UPDATE_SCORE, (new_balance, new_task, login)) return new_balance
def gen_keys(): rs = gmpy2.random_state(hash(gmpy2.random_state())) P = gmpy2.mpz_urandomb(rs, mpz('256')) P = gmpy2.next_prime(P) Q = gmpy2.mpz_urandomb(rs, mpz('256')) Q = gmpy2.next_prime(Q) N = P*Q Fi = (P-1)*(Q-1) Pkey = gmpy2.mpz_random(rs, Fi) while not (gmpy2.gcd(Fi, Pkey) == 1): Pkey = gmpy2.mpz_random(rs, Fi) Skey = gmpy2.invert(Pkey, Fi) print('Публичный ключ: ') print(Pkey) print('Приватный ключ:') print(Skey) print('N:') print(N)
def get_prime_list(): """:returns an array of primes of lengths specified in n_list Note that these primes are not uniformly distributed: the probability of a prime to be picked is proportional to the distance between this prime and the previous prime. """ print("Getting list of primes...") prime_list = [next_prime(get_rand(n)) for n in n_list] print("Done.") return prime_list
def generate_q(): q = gmp.mpz_urandomb(gmp.random_state(random.randint(0, 367263292)), N) while not gmp.is_prime(q): q = gmp.next_prime(q) if no_bits(q) != N: q = gmp.mpz_urandomb( gmp.random_state(random.randint(0, 367263292)), N) return q
def next(self): """Returns a prime number, which has not been used yet. Returns: int: Prime number, which has not been used yet in this session. """ self.last_prime = gm.next_prime(self.last_prime) return self.last_prime
def primes(B): p = 2 tmp = [] #n=0 while p <= B: tmp.append(p) p = next_prime(p) #n += 1 return tmp
def __getSafePrimes(n_len): rng = secrets.SystemRandom() prime_ = gmpy2.mpz(rng.getrandbits(n_len - 1)) prime_ = gmpy2.bit_set(prime_, n_len - 2) while True: prime_ = gmpy2.next_prime(prime_) prime = 2 * prime_ + 1 if gmpy2.is_prime(prime, 25): break return prime_, prime
def key_gen(self, bits, prime_numbers=4): delta = randint(5, 15) bit_prime = int(bits // prime_numbers) P = [next_prime(number.getPrime(bit_prime) + 1)] for i in range(1, prime_numbers): P.append(next_prime(P[i - 1] * delta)) n = self.__compute_module(P) phi = self.__compute_phi(P) for d_next in count(int(pow(P[0] // 2, 0.5)), -1): g, e, __ = gcdext(d_next, phi) if (1 < e < n) and (g == 1) and (gcd(phi, e) == 1): d = d_next break self.public_key = (e, n) self.secret_key = (d, n)
def main(): Q = mpz(randint(3, 65535)) Q = gmpy2.next_prime(Q) N = mpz(randint(3, 65535)) N = gmpy2.next_prime(N) print('Выберем простые числа Q = {} и N = {}'.format(Q, N)) X = mpz(randint(100, 65535)) print('Алиса генерирует случайное число x = ' + X.digits(10)) Y = mpz(randint(100, 65535)) print('Боб генерирует случайное число y = ' + Y.digits(10)) A = gen_DH_pow(X, Q, N) print('Алиса вычисляет число A и передает его Бобу') print('Атакующий видит число A = ' + A.digits(10)) B = gen_DH_pow(Y, Q, N) print('Боб вычисляет число B и передает его Алисе') print('Атакующий видит число B = ' + B.digits(10)) Ka = gen_DH_key(B, X, N) Kb = gen_DH_key(A, Y, N) print('Алиса вычисляет секретный ключ K = ' + Ka.digits(10)) print('Боб вычисляет секретный ключ K = ' + Kb.digits(10))
def goldbach(n): """teste la conjecture de Golbach en tentant de décomposer n pair (>2) en 2 nb premiers""" x = 3 while True: # calcul de y et test de primalité y = n-x if gmpy2.is_prime(y,20): return (n,[int(x),int(y)]) # On prend le nombre premier suivant x = gmpy2.next_prime(x)
def main(): args = parse_args() prime_length_bits = args.key_strength_bytes * 4 p = gmpy2.next_prime((1<<prime_length_bits) + random.getrandbits(prime_length_bits)) q = gmpy2.mpz((1<<prime_length_bits) + random.getrandbits(prime_length_bits)) N = p*q # Now try to find qs that give us a modulus with the payload somewhere in the middle encoded_modulus = mpz_to_base64(N) payload = clean_payload(args.message) start_index = len(encoded_modulus)//2 - len(payload) + 10 # Magic number. Reduce if having a bad day. success = False while not success: # Splice payload into the initial modulus approx_modulus = base64_to_long(splice(encoded_modulus, start_index, payload)) # Find the next value of q that is prime start_q = gmpy2.mpz(approx_modulus)/p next_q = gmpy2.next_prime(start_q) candidate_modulus = next_q * p # Check if the payload is preserved if payload in mpz_to_base64(candidate_modulus): print 'Success! Writing private key to {}'.format(args.key_file) print 'Your authorized_keys entry is below:' authorized_key = build_keys(candidate_modulus, p, next_q, args.key_file) highlight_print(authorized_key, payload) break # If not, shift the payload to the left and try again if start_index < 20: print 'No cookie for you, sorry!' break start_index -= 1
def pe500(e, M): prd = 1 np = 3 queue = [np] while e - 1 > math.log(math.log(np, 2), 2): if queue[0] == np: bisect.insort(queue, np ** 2) np = gmpy2.next_prime(np) bisect.insort(queue, np) else: bisect.insort(queue, queue[0] ** 2) prd = (prd * queue.pop(0)) % M e -= 1 return (pow(2, 2 ** e - 1, M) * prd) % M
def getprimeover(N): """Return a random N-bit prime number using the System's best Cryptographic random source. Use GMP if available, otherwise fallback to PyCrypto """ if HAVE_GMP: randfunc = random.SystemRandom() r = gmpy2.mpz(randfunc.getrandbits(N)) r = gmpy2.bit_set(r, N - 1) return int(gmpy2.next_prime(r)) elif HAVE_CRYPTO: return number.getPrime(N, os.urandom) else: raise NotImplementedError("No pure python implementation sorry")
def gmpyPrimes(n): primes = [] prime = 2 toPrint = 0 while prime <= n: prime = gmpy2.next_prime(prime) primes.append(prime) toPrint += 1 if toPrint == 10000: print(prime) toPrint = 0 return primes
def getprimeover(N): """Return a random N-bit prime number using the System's best Cryptographic random source. Use GMP if available, otherwise fallback to PyCrypto """ if HAVE_GMP: randfunc = random.SystemRandom() r = gmpy2.mpz(randfunc.getrandbits(N)) r = gmpy2.bit_set(r, N - 1) return int(gmpy2.next_prime(r)) elif HAVE_CRYPTO: return number.getPrime(N, os.urandom) else: randfunc = random.SystemRandom() n = randfunc.randrange(2**(N-1), 2**N) | 1 while not is_prime(n): n += 2 return n
def fsst(x): try: x=gp.mpz(x) except TypeError: print("参数必须是整数") t=[] p=1 while x!=1: p=gp.next_prime(p) while x%p==0: t.append(p) x//=p t=list(map(abcd,t)) while len(t)>1: a,b,c,d=t.pop(0) w,x,y,z=t.pop(0) t.append((a*w+b*x+c*y+d*z,a*x-b*w-c*z+d*y,a*y+b*z-c*w-d*x,a*z-b*y+c*x-d*w)) a,b,c,d=t[0] return a,b,c,d
def isprime(n): ''' Tests for primality of n trying first fastprime and then a slower but accurate algorithm. Time complexity is O(N**3) (assuming quadratic multiplication), where n has N digits. Returns the primality of n (True or False).''' if not fastprime(n): return False elif n < SMALLEST_COUNTEREXAMPLE_FASTPRIME: return True do_loop = False j = 1 d = n >> 1 a = 2 bound = int(0.75 * math.log(math.log(n)) * math.log(n)) + 1 while not d & 1: d >>= 1 j += 1 while a < bound: a = next_prime(a) p = atdn(a, d, n) if p == 1 or p == n - 1: continue for _ in range(j): p = (p * p) % n if p == 1: return False elif p == n - 1: do_loop = True break if do_loop: do_loop = False continue return False return True
def factorize(x=c): r''' (Takes about 25ms, on c, on a first-generation Macbook Pro) >>> factorize(a) [3, 41] >>> factorize(b) [2, 2, 2, 3, 19] >>> ''' import gmpy2 as _g savex=x prime=2 x=_g.mpz(x) factors=[] while x>=prime: newx,mult=x.remove(prime) if mult: factors.extend([int(prime)]*mult) x=newx prime=_g.next_prime(prime) for factor in factors: assert _g.is_prime(factor) from operator import mul assert reduce(mul, factors)==savex return factors
# get p value fi = open('pCurr2.txt', 'r') p = mpz(fi.readline()) fi.close() print p.digits(10) # loop for prime while p < 15000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000: # get remainder of div(n, p) rem = gmpy2.t_mod(n, p) if rem == 0: q = gmpy2.c_div(n, p) f = open('pResult.txt', 'a') f.write("p = " + p.digits(10) + "\n") f.write("q = " + q.digits(10) + "\n") f.write("n = " + n.digits(10) + "\n") f.close() fi = open('pCurr2.txt', 'w') fi.write(p.digits(10)) fi.close() fv = open('pValue2.txt', 'a') fv.write(p.digits(10) + "\n") fv.close() sys.exit() p = gmpy2.next_prime(p)
def primes(): n = 2 while True: yield n n = gmpy2.next_prime(n)
primes=[] def numcat(a,b): return int(str(a)+str(b)) #return int(math.pow(10,(int(math.log(b,10)) + 1)) * a + b) j=2 while (j<27000): j=gmpy2.next_prime(j) primes.append(j) primefits=[] for i in range(len(primes)): primefits.append([primes[l] for l in range(i+1,len(primes)) if (gmpy2.is_prime(numcat(primes[i],primes[l])) and gmpy2.is_prime(numcat(primes[l],primes[i]))) ]) hits=[] for fit1 in primefits: if not (len(fit1)): continue for fit2 in fit1: index1=primes.index(fit2) if not len(primefits[index1]):
cur=conn.cursor() cur.execute("SELECT * FROM new_primes ORDER BY Number DESC LIMIT 1") row=cur.fetchone() counter=int(row[0]) prime=int(row[1]) print("Starting at:",prime) except Exception: print("ERROR: Could not connect to mySQL database.") counter=0 index=0 if counter: print("Press ^C to exit.\n") try: while True: counter+=1 prime=next_prime(prime) query="INSERT INTO `new_primes`(`Number`, `Primes`) VALUES ("+str(counter)+","+str(prime)+")" cur.execute(query) index+=1 if index>20000: conn.commit() index=0 except KeyboardInterrupt: print("User terminated program.") except Exception: print("ERROR: Program quit unexpectedly.") conn.commit() print("Last number stored:",prime) cur.close() conn.close() print("Database connection closed.")
def test_fermat_factoring(self): q = getPrime(512) p = gmpy2.next_prime(q + random.randint(1 << 64, 1 << 128)) self.assertEqual((p , q), number.fermat_factoring(p * q))
p_max = gmpy2.mul(p_max, 2) print "p_max= " print p_max.digits(10) # calculate p_min p_min = proot(1, dist, -(n - 1)) print "p_min= " print p_min.digits(10) # start finding prime if gmpy2.is_prime(p_min): p = p_min else: p = gmpy2.next_prime(p_min) # loop through prime numbers from p_min to p_max while p < p_max: # get remainder of div(n, p) rem = gmpy2.t_mod(n, p) if rem == 0: print "\nresult= " print "p= " print p.digits(10) print "q= " print gmpy2.c_div(n, p) sys.exit() p = gmpy2.next_prime(p)
def sub_sub_sure_factors(f, u, curve_parameter): '''Finds all factors that can be found using ECM with a smoothness bound of u and sigma and give curve parameters. If that fails, checks for being a prime power and does Fermat factoring as well. Yields factors.''' while not (f & 1): yield 2 f >>= 1 while not (f % 3): yield 3 f = f // 3 if isprime(f): yield f return log_u = math.log(u) u2 = int(_7_OVER_LOG_2 * u * log_u / math.log(log_u)) primes = [] still_a_chance = True log_mo = math.log(f + 1 + sqrt(f << 2)) g = gcd(curve_parameter, f) if g not in (1, f): for factor in sub_sub_sure_factors(g, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(f//g, u, curve_parameter): yield factor return g2 = gcd(curve_parameter**2 - 5, f) if g2 not in (1, f): for factor in sub_sub_sure_factors(g2, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(f // g2, u, curve_parameter): yield factor return if f in (g, g2): yield f while still_a_chance: p1 = get_points([curve_parameter], f) for prime in primes: p1 = multiply(p1, prime, f) if not isinstance(p1, list): if p1 != f: for factor in sub_sub_sure_factors(p1, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(f//p1, u, curve_parameter): yield factor return else: still_a_chance = False break if not still_a_chance: break prime = 1 still_a_chance = False while prime < u2: prime = next_prime(prime) should_break = False for _ in range(int(log_mo / math.log(prime))): p1 = multiply(p1, prime, f) if not isinstance(p1, list): if p1 != f: for factor in sub_sub_sure_factors(p1, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(f//p1, u, curve_parameter): yield factor return else: still_a_chance = True primes.append(prime) should_break = True break if should_break: break for i in range(2, int(math.log(f) / LOG_2) + 2): r = root(f, i) if r[1]: for factor in sub_sub_sure_factors(r[0], u, curve_parameter): for _ in range(i): yield factor return a = 1 + sqrt(f) bsq = a * a - f iter = 0 while bsq != sqrt(bsq)**2 and iter < 3: a += 1 iter += 1 bsq += a + a - 1 if bsq == sqrt(bsq)**2: b = sqrt(bsq) for factor in sub_sub_sure_factors(a - b, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(a + b, u, curve_parameter): yield factor return yield f return
def mainloop(n, u, p1): ''' Input: n -- an integer to (try) to factor. u -- the phase 1 smoothness bound p1 -- a list of sigma parameters to try Output: A factor of n. (1 is returned on faliure). Notes: 1. Other parameters, such as the phase 2 smoothness bound are selected by the mainloop function. 2. This function uses batch algorithms, so if p1 is not long enough, there will be a loss in efficiency. 3. Of course, if p1 is too long, then the mainloop will have to use more memory. [The memory is polynomial in the length of p1, log u, and log n].''' k = inv_const(n) log_u = math.log(u) log_log_u = math.log(log_u) log_n = math.log(n) u2 = int(_7_OVER_LOG_2 * u * log_u / log_log_u) ncurves = len(p1) w = int(math.sqrt(_3_OVER_LOG_2 * ncurves / k) - 0.5) number_of_primes = int((ncurves << w) * math.sqrt(LOG_4_OVER_9 * log_n / k) / log_u) # Lagrange multipliers! number_of_primes = min(number_of_primes, int((log_n / math.log(log_n))**2 * ncurves / log_u), int(u / log_u)) number_of_primes = max(number_of_primes, 1) m = math.log(number_of_primes) + log_log_u w = min(w, int((m - 2 * math.log(m) + LOG_3_MINUS_LOG_LOG_2) / LOG_2)) w = max(w, 1) max_order = n + sqrt(n << 2) + 1 # By Hasse's theorem. det_bound = ((1 << w) - 1 + ((w & 1) << 1)) // 3 log_mo = math.log(max_order) p = list(range(number_of_primes)) prime = mpz(2) p1 = get_points(p1, n) if not isinstance(p1, list): return p1 for _ in range(int(log_mo / LOG_2)): p1 = double(p1, n) if not isinstance(p1, list): return p1 for i in range(1, det_bound): prime = (i << 1) + 1 if isprime(prime): for _ in range(int(log_mo / math.log(prime))): p1 = multiply(p1, prime, n) if not isinstance(p1, list): return p1 while prime < sqrt(u) and isinstance(p1, list): for i in range(number_of_primes): prime = next_prime(prime) p[i] = prime ** max(1, int(log_u / math.log(prime))) p1 = fast_multiply(p1, prod(p), n, w) if not isinstance(p1, list): return p1 while prime < u and isinstance(p1, list): for i in range(number_of_primes): prime = next_prime(prime) p[i] = prime p1 = fast_multiply(p1, prod(p), n, w) if not isinstance(p1, list): return p1 del p small_jump = int(greatest_n((1 << (w + 2)) // 3)) small_jump = max(120, small_jump) big_jump = 1 + (int(sqrt((5 << w) // 21)) << 1) total_jump = small_jump * big_jump big_multiple = max(total_jump << 1, ((int(next_prime(prime)) - (total_jump >> 1)) / total_jump) * total_jump) big_jump_2 = big_jump >> 1 small_jump_2 = small_jump >> 1 product = ONE psmall_jump = multiply(p1, small_jump, n) if not isinstance(psmall_jump, list): return psmall_jump ptotal_jump = multiply(psmall_jump, big_jump, n) if not isinstance(ptotal_jump, list): return ptotal_jump pgiant_step = multiply(p1, big_multiple, n) if not isinstance(pgiant_step, list): return pgiant_step small_multiples = [None] for i in range(1, small_jump >> 1): if gcd(i, small_jump) == 1: tmp = multiply(p1, i, n) if not isinstance(tmp, list): return tmp for i in range(len(tmp)): tmp[i] = tmp[i][0] small_multiples.append(tuple(tmp)) else: small_multiples.append(None) small_multiples = tuple(small_multiples) big_multiples = [None] for i in range(1, (big_jump + 1) >> 1): tmp = multiply(psmall_jump, i, n) if not isinstance(tmp, list): return tmp big_multiples.append(to_tuple(tmp)) big_multiples = tuple(big_multiples) psmall_jump = to_tuple(psmall_jump) ptotal_jump = to_tuple(ptotal_jump) while big_multiple < u2: big_multiple += total_jump center_up = big_multiple center_down = big_multiple pgiant_step = add(ptotal_jump, pgiant_step, n) if not isinstance(pgiant_step, list): return pgiant_step prime_up = next_prime( mpz( big_multiple - small_jump_2 ) ) while prime_up < big_multiple + small_jump_2: s = small_multiples[ int( abs( int( prime_up ) - big_multiple ) ) ] for j in range(ncurves): if s is None: product *= pgiant_step[j][0] else: product *= pgiant_step[j][0] - s[j] product %= n prime_up = next_prime(prime_up) for i in range(1, big_jump_2 + 1): center_up += small_jump center_down -= small_jump pmed_step_up, pmed_step_down = add_sub_x_only(big_multiples[i], pgiant_step, n) if pmed_step_down is None: return pmed_step_up while prime_up < center_up + small_jump_2: s = small_multiples[ int( abs( int( prime_up ) - center_up ) ) ] for j in range(ncurves): product *= pmed_step_up[j] - s[j] product %= n prime_up = next_prime(prime_up) prime_down = next_prime(center_down - small_jump_2) while prime_down < center_down + small_jump_2: s = small_multiples[abs(int(prime_down) - center_down)] for j in range(ncurves): product *= pmed_step_down[j] - s[j] product %= n prime_down = next_prime(prime_down) if gcd(product, n) != 1: return gcd(product, n) return 1