def factor_bounded_pm1(n, b, degree='auto'): print 'start' a = 2 i = 0 q = 2 if degree == 'auto': while q < b: i += 1 if i % 1000 == 0: print 'Progress:', q, b base = q**int(math.floor(1 / math.log(q, n))) a = pow(a, base, n) g = gmpy.gcd(a - 1, n) if g != 1 and g != n: return int(g) q = gmpy.next_prime(q) return None else: while q < b: i += 1 if i % 1000 == 0: print 'Progress:', q, b base = q**degree a = pow(a, base, n) g = gmpy.gcd(a - 1, n) if g != 1 and g != n: return int(g) q = gmpy.next_prime(q) return None
def factor(_m,_r,_n): for i in range(2,1000): if _r%i == 0: t = pow(_m,_r//i,_n) if gmpy.gcd(t-1,_n) != 1 and gmpy.gcd(t-1,_n) != _n: p = gmpy.gcd(t-1,_n) q = _n//gmpy.gcd(t-1,_n) break return p,q
def is_prime_fermat(n,s): #n,s prirozena '1=prime, 0=sloz' for i in xrange(s): a = random.randint(2,n-2) #zvol nahodne cele cislo mezi 2 a n-2 vcetne print a,gmpy.gcd(a,n), pow(a,n-1,n) if gmpy.gcd(a,n) != 1: return (i, 0) #je slozene if pow(a,n-1,n) != 1: #pouzijeme modularni mocneni return (i, 0) #je slozene return (-1, 1) #proslo testem
def is_prime_fermat(n, s): #n,s prirozena '1=prime, 0=sloz' for i in xrange(s): a = random.randint(2, n - 2) #zvol nahodne cele cislo mezi 2 a n-2 vcetne print a, gmpy.gcd(a, n), pow(a, n - 1, n) if gmpy.gcd(a, n) != 1: return (i, 0) #je slozene if pow(a, n - 1, n) != 1: #pouzijeme modularni mocneni return (i, 0) #je slozene return (-1, 1) #proslo testem
def gen_key(bits=1024): while True: p = get_random_prime(bits) q = get_random_prime(bits) if p != q and gmpy.gcd(p * q, (p - 1) * (q - 1)) == 1: break n = p * q l = int(gmpy.lcm(p - 1, q - 1)) while True: g = randint(1, n**2) if gmpy.gcd(g, n**2) == 1: break u = gmpy.invert(L(pow(g, l, n**2), n), n) return (n, g), (l, u)
def main(max_base, separator='\t'): f = urllib.urlopen("http://bealstreasure.com/members/getwork.php?username="******"&max_base=" + str(max_base)).read() warning("f: ", f) tmp_vals = f.split(",") warning("tmp_vals: ", tmp_vals) (m, n, set_id) = (int(tmp_vals[0]),int(tmp_vals[1]),tmp_vals[2]) max_exp = max([m, n]) table = initial_data_table(max_base, m, n) if (max_exp < max([m, n]) + 10): table = initial_data_table(max_base, m, n) max_exp = max([m, n]) powx, powy = initial_data_pow(max_base, m, n) for x in xrange(1, max_base): powx_tmp = powx[x] for y in xrange(1, x): if gcd(x,y) > 1: continue sum = powx_tmp + powy[y] zr = table.get(sum) if zr: report(x, m, y, n) f = urllib.urlopen("http://bealstreasure.com/members/savework.php?result=false&memory=" + str(memory) + "&id=" + str(set_id)).read() printing("(%d, %d, %s)" % (m, n, set_id))
def solve(A, low, high): A = sorted(set(A)) N = len(A) G = [0] * N G[-1] = A[-1] for i in reversed(range(N-1)): G[i] = int(gmpy.gcd(G[i+1], A[i])) #print 'A:', A, ' low=%d high=%d' % (low, high) #print 'G:', G if low <= A[0]: x = solve1(low, A[0], 1, G[0]) if x is not None: return x lcm = A[0] for i in xrange(N-1): x = solve1(max(low, A[i]), min(high, A[i+1]), lcm, G[i+1]) if x is not None: return x lcm = int(gmpy.lcm(lcm, A[i+1])) if lcm > high: break if low <= lcm <= high: return lcm return 'NO'
def recover_rsa_modulus_from_signatures(m1, s1, m2, s2, e=0x10001): """ Calculates the modulus used to produce RSA signatures from two known message/signature pairs and the public exponent. Since the most common public exponent is 65537, we default to that. Parameters: m1 - (string) The first message s1 - (string) The signature of the first message as an unencoded string m2 - (string) The second message s2 - (string) The signature of the second message e - (int) The exponent to use Returns the modulus as an integer, or False upon failure. """ m1 = string_to_long(m1) s1 = string_to_long(s1) m2 = string_to_long(m2) s2 = string_to_long(s2) gcd_result = gmpy.gcd( s1 ** e - m1, s2 ** e - m2 ) if gcd_result < s1 or gcd_result < s2: # The modulus can never be smaller than our signature. # If this happens, we have been fed bad data. return False else: return int(gcd_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 xrange(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 find_rpf_between(max_denominator, lo, hi): for denominator in tqdm(range(1, max_denominator + 1)): for numerator in range(int(denominator * lo), int(denominator * hi) + 1): ratio = numerator / denominator if lo < ratio < hi and gcd(numerator, denominator) == 1: yield (numerator, denominator)
def beal_parallel(max_base, queue): m=200; n=200; max_exp = max([m, n]) table = initial_data_table(max_base, m, n) (m, n, set_id) = queue.get() while(True): print '(%d, %d, %s)' % (m, n, set_id) if (max_exp < max([m, n]) + 10): table = initial_data_table(max_base, m, n) max_exp = max([m, n]) powx, powy = initial_data_pow(max_base, m, n) for x in xrange(1, max_base): powx_tmp = powx[x] for y in xrange(1, x): if gcd(x,y) > 1: continue sum = powx_tmp + powy[y] zr = table.get(sum) if zr: report(x, m, y, n) f = urllib.urlopen("http://bealstreasure.com/members/savework.php?result=false&memory=" + str(memory) + "&id=" + str(set_id)).read() (m, n, set_id) = queue.get()
def solve(A, low, high): A = sorted(set(A)) N = len(A) G = [0] * N G[-1] = A[-1] for i in reversed(range(N - 1)): G[i] = int(gmpy.gcd(G[i + 1], A[i])) #print 'A:', A, ' low=%d high=%d' % (low, high) #print 'G:', G if low <= A[0]: x = solve1(low, A[0], 1, G[0]) if x is not None: return x lcm = A[0] for i in xrange(N - 1): x = solve1(max(low, A[i]), min(high, A[i + 1]), lcm, G[i + 1]) if x is not None: return x lcm = int(gmpy.lcm(lcm, A[i + 1])) if lcm > high: break if low <= lcm <= high: return lcm return 'NO'
def no_rand2(n=0): random.seed(22409) for i in range(n, 50000): print i p = number.getPrime(512, randfunction) if p == gmpy.gcd(p, n10): print 'success' return p
def pollard_pm1(n, B1=100, B2=1000): # TODO: What are the best default bounds and way to increment them? if isprime(n): return n m = ispower(n) if m: return m while True: pg = primegen() q = 2 # TODO: what about other initial values of q? p = pg.next() while p <= B1: q, p = pow(q, p**ilog(B1, p), n), pg.next() g = gcd(q-1, n) if 1 < g < n: return g while p <= B2: q, p = pow(q, p, n), pg.next() g = gcd(q-1, n) if 1 < g < n: return g # These bounds failed. Increase and try again. B1 *= 10 B2 *= 10
def gcd(*args): """ Calculate GCD Args: *args : Some Integers Return: GCD of *args """ return int(reduce(lambda x, y: gmpy.gcd(x, y), args[1:], args[0]))
def pollard(n): a = 2 b = 2 while True: a = pow(a, b, n) d = gmpy.gcd(n, a - 1) if d > 1: return d b += 1
def findN(): m1 = 0xdead m2 = 0x1337 m12 = m1**2 m22 = m2**2 c1, c2, c12, c22 = map(calcAx, (m1, m2, m12, m22)) return int(gmpy.gcd(c2*c2-c22, c1*c1-c12))
def encrypt(pk, m): assert m < pk[0] while True: r = randint(1, pk[0]) if gmpy.gcd(r, pk[0]) == 1: break c1 = pow(pk[1], m, pk[0]**2) c2 = pow(r, pk[0], pk[0]**2) return (c1 * c2) % pk[0]**2
def find_rpf_less_than(max_denominator, fraction): greatest = 0 rpf = (0, 1) for denominator in tqdm(range(1, max_denominator + 1)): numerator = int(denominator * fraction) ratio = numerator / denominator if greatest < ratio < 3 / 7 and gcd(numerator, denominator) == 1: greatest = ratio rpf = (numerator, denominator) return rpf
def find_close(n): sq = gmpy.sqrt(n) sq = sq - 10 if sq % 2 == 0: sq = sq - 1 for i in range(10000): sq = sq + 2 if sq == gmpy.gcd(sq, n): return sq return None
def run(self, key, testRun, keyReference, client, makePerm=True): res = gmp.gcd(self.product % key.n, key.n) if res == 1: status = 1 outputText = 'No small prime factor up to ' + str(self.parameter) + ' found. ' else: status = -2 outputText = 'At least one small prime factor was found. ' return status, outputText, []
def decode(NA, CA, NB): p = gmpy.gcd(NA, NB) q = NA / p assert(p*q == NA) # print p # print q phi = (p-1)*(q-1) d = gmpy.invert(e, phi) m = pow(CA, d, NA) assert(pow(m, e, NA) == CA) print ("%01024x" % m).decode('hex')
def apply(self, ns, evaluation): 'GCD[ns___Integer]' ns = ns.get_sequence() result = 0 for n in ns: value = n.get_int_value() if value is None: return result = gcd(result, value) return Integer(result)
def find_p_q(): for i in range(16): for j in range(16): if i <> j: n1 = gmpy.mpz(ns[i]) n2 = gmpy.mpz(ns[j]) p = gmpy.gcd(n1, n2) if p <> 1: q = n1 / p print i print 'p', p print 'q', q
def williams_pp1(n): if isprime(n): return n m = ispower(n) if m: return m for v in count(1): for p in primegen(): e = ilog(isqrt(n), p) if e == 0: break for _ in xrange(e): v = mlucas(v, p, n) g = gcd(v - 2, n) if 1 < g < n: return g if g == n: break
def pollardRho_brent(n): if isprime(n): return n g = n while g == n: y, c, m, g, r, q = randrange(1, n), randrange(1, n), randrange(1, n), 1, 1, 1 while g==1: x, k = y, 0 for i in xrange(r): y = (y**2 + c) % n while k < r and g == 1: ys = y for i in xrange(min(m, r-k)): y = (y**2 + c) % n q = q * abs(x-y) % n g, k = gcd(q, n), k+m r *= 2 if g==n: while True: ys = (ys**2+c)%n g = gcd(abs(x-ys), n) if g > 1: break return g
def ecm(n, B1=10, B2=20): # TODO: Determine the best defaults for B1 and B2 and the best way to increment them and iters # "Modern" ECM using Montgomery curves and an algorithm analogous to the two-phase variant of Pollard's p-1 method # TODO: We currently compute the prime lists from the sieve as we need them, but this means that we recompute them at every # iteration. While it would not be particularly efficient memory-wise, we might be able to increase time-efficiency # by computing the primes we need ahead of time (say once at the beginning and then once each time we increase the # bounds) and saving them in lists, and then iterate the inner while loops over those lists. if isprime(n): return n m = ispower(n) if m: return m iters = 1 while True: for _ in xrange(iters): # TODO: multiprocessing? # TODO: Do we really want to call the randomizer? Why not have seed be a function of B1, B2, and iters? # TODO: Are some seeds better than others? seed = randrange(6, n) u, v = (seed**2 - 5) % n, 4*seed % n p = pow(u, 3, n) Q, C = (pow(v-u,3,n)*(3*u+v) % n, 4*p*v % n), (p, pow(v,3,n)) pg = primegen() p = pg.next() while p <= B1: Q, p = ecmul(p**ilog(B1, p), Q, C, n), pg.next() g = gcd(Q[1], n) if 1 < g < n: return g while p <= B2: # "There is a simple coding trick that can speed up the second stage. Instead of multiplying each prime times Q, # we iterate over i from B1 + 1 to B2, adding 2Q at each step; when i is prime, the current Q can be accumulated # into the running solution. Again, we defer the calculation of the greatest common divisor until the end of the # iteration." TODO: Implement this trick and compare performance. Q = ecmul(p, Q, C, n) g *= Q[1] g %= n p = pg.next() g = gcd(g, n) if 1 < g < n: return g # This seed failed. Try again with a new one. # These bounds failed. Increase and try again. B1 *= 3 B2 *= 3 iters *= 2
def encrypt_r(self, value, player_id=None, random_elm=None): """Encryption of the given value. If player_id is given, encrypts using public key of that player, otherwise just use public key of the player itself. The encryption requires some randomness in the form of an element in Zn*. If random_elm is given, it is used as random element. Otherwise, a random element is generated using the pseudo-random generator given when the ModifiedPaillier object was constructed. """ assert isinstance(value, int) or isinstance(value, long), \ "paillier: encrypts only integers and longs, got %s" % \ value.__class__ if not player_id: player_id = self.runtime.id n = self.runtime.players[player_id].pubkey['n'] min = -(n - 1) / 2 max = (n - 1) / 2 assert min <= value <= max, \ "paillier: plaintext %d outside legal range [-(n-1)/2 " \ "; (n-1)/2] = [%d ; %d]" % (value, min, max) # Here we verify that random_elm is either None or in Zn*. But # for realistical parameters, we can save time by not doing # this, since for large n = pq, it is extremely unlikely that # a random element in Zn is not also a member of Zn*. if random_elm == None: while True: random_elm = self.random.randint(1, long(n)) if gcd(random_elm, n) == 1: break elif not gcd(random_elm, n) == 1: raise Exception("Random element must be an element in Zn*") pubkey = self.runtime.players[player_id].pubkey return random_elm, pypaillier.encrypt_r(self._f(value, n), random_elm, pubkey)
def encrypt_r(self, value, player_id=None, random_elm=None): """Encryption of the given value. If player_id is given, encrypts using public key of that player, otherwise just use public key of the player itself. The encryption requires some randomness in the form of an element in Zn*. If random_elm is given, it is used as random element. Otherwise, a random element is generated using the pseudo-random generator given when the ModifiedPaillier object was constructed. """ assert isinstance(value, int) or isinstance(value, long), \ "paillier: encrypts only integers and longs, got %s" % \ value.__class__ if not player_id: player_id = self.runtime.id n = self.runtime.players[player_id].pubkey['n'] min = -(n - 1) / 2 max = (n - 1) / 2 assert min <= value <= max, \ "paillier: plaintext %d outside legal range [-(n-1)/2 " \ "; (n-1)/2] = [%d ; %d]" % (value, min, max) # Here we verify that random_elm is either None or in Zn*. But # for realistical parameters, we can save time by not doing # this, since for large n = pq, it is extremely unlikely that # a random element in Zn is not also a member of Zn*. if random_elm == None: while True: random_elm = self.random.randint(1, long(n)) if gcd(random_elm, n) == 1: break elif not gcd(random_elm, n) == 1: raise Exception("Random element must be an element in Zn*") pubkey = self.runtime.players[player_id].pubkey return random_elm, pypaillier.encrypt_r( self._f(value, n), random_elm, pubkey)
def check_z(self, results): self.function_count[13] += 1 z = results[0].value % self.n_revealed #print "z = " + str(z) z_n = gmpy.gcd(z, self.n_revealed) if z_n == 1: #print "gcd(z, N) = 1, start generating e,d" self.e = 2**16 + 1 #print "e = " + str(self.e) self.generate_l() else: #print "gcd(z, N) != 1, restart with generating p" self.prime_pointer = 0 self.generate_p()
def run(self, keys, testRun, keyReferences, client, makePerm=True): tree=[[]] moduli = [] for key, keyReference in zip(keys, keyReferences): z = mpz(key.modulus) tree[0].append(z) moduli.append((z, keyReference)) while len(tree[-1])>1: row=[] for k in range(0,len(tree[-1]),2): if k+1<len(tree[-1]): row.append(tree[-1][k]*tree[-1][k+1]) else: row.append(tree[-1][k]) tree.append(row) for k in range(len(tree)-2,-1,-1): for i in range(0,len(tree[k])): tree[k][i]= tree[k+1][i//2] % tree[k][i]**2 res=[] for k in range(0,len(tree[0])): res.append( gmp.gcd(moduli[k][0]**2, tree[0][k]) // moduli[k][0]) revokes = [] for k in range(0,len(res)): if res[k]>1: #print 'CommonGCD found' #print moduli[k][1] #print res[k] == moduli[k][0] #print res[k] #print '---------------------------------' revokes.append(keyReferences[k]) if len(revokes) == 0: status = 1 outputText = 'No common GCD found' else: status = -2 outputText = 'Common GCDs found' return status, outputText, revokes
def generateKeys(bit_length): """ Generate a Paillier keypair of desired bit length. *bitlength* the desired bitlength for the generated key """ # Generate an RSA modulus if bit_length <= 2: bit_length = 3 p = randomPrime(bit_length / 2) q = p n = p * q while p == q or gcd(n, (p - 1) * (q - 1)) != 1: q = randomPrime(bit_length / 2) n = p * q # lm = lambda lm = (p - 1) * (q - 1) # Generator g of Z*/n^2Z. g = n + 1 # Precompute mu for decryption mu = invert(lm, n) # pubkey, privkey psq = p**2 qsq = q**2 qsq_inv = invert(qsq, psq) return { 'n': n, 'g': g, 'nsq': n * n }, { 'n': n, 'nsq': n * n, 'g': g, 'lm': lm, 'mu': mu, 'p': p, 'q': q, 'psq': psq, 'phi_psq': psq - p, 'qsq': qsq, 'phi_qsq': qsq - q, 'qsq_inv': qsq_inv }
def parallel_invert(l, n): '''Inverts all elements of a list modulo some number, using 3(n-1) modular multiplications and one inversion. Returns the list with all elements inverted modulo 3(n-1).''' l_ = l[:] for i in xrange(len(l)-1): l[i+1] = (l[i] * l[i+1]) % n inv = invert(l[-1], n) if inv == 0: return gcd(l[-1], n) for i in xrange(len(l)-1, 0, -1): l[i] = (inv * l[i-1]) % n inv = (inv * l_[i]) % n l[0] = inv return l
def parallel_invert(l, n): '''Inverts all elements of a list modulo some number, using 3(n-1) modular multiplications and one inversion. Returns the list with all elements inverted modulo 3(n-1).''' l_ = l[:] for i in xrange(len(l) - 1): l[i + 1] = (l[i] * l[i + 1]) % n inv = invert(l[-1], n) if inv == 0: return gcd(l[-1], n) for i in xrange(len(l) - 1, 0, -1): l[i] = (inv * l[i - 1]) % n inv = (inv * l_[i]) % n l[0] = inv return l
def generate_keys(self): self.p = self.rand_prime(self.key_length/2) while True: self.q = self.rand_prime(self.key_length/2) if not (self.p == self.q): break self.n = self.p * self.q self.nsq = self.n * self.n self.lam = lcm(self.p-1, self.q-1) while True: self.g = randint(1, self.nsq) if gcd(Paillier.L(pow(self.g, self.lam, self.n), self.n), self.n): break self.public_key = {'n':self.n, 'g':self.g} self.private_key = {'n':self.n, 'g':self.g, 'lam':self.lam}
def is_prime_ss(n, s): #n,s prirozena, n>3 liche ''' return (rounds, res): - rounds is -1 if it passed all tests (ie: probably prime) ''' for i in xrange(0, s): # 0,1,...,s-1 a = random.randint(2, n - 2) #nah. c. mezi 2 a n-2 if gmpy.gcd(a, n) != 1: return (i, 0) #je slozene p = pow(a, (n - 1) / 2, n) if p == n - 1: p = -1 if not gmpy.jacobi(a, n) == p: return (i, 0) #je slozene return (-1, 1) #n proslo testem
def generate_keys(self): self.p = self.rand_prime(self.key_length / 2) while True: self.q = self.rand_prime(self.key_length / 2) if not (self.p == self.q): break self.n = self.p * self.q self.nsq = self.n * self.n self.lam = lcm(self.p - 1, self.q - 1) while True: self.g = randint(1, self.nsq) if gcd(Paillier.L(pow(self.g, self.lam, self.n), self.n), self.n): break self.public_key = {'n': self.n, 'g': self.g} self.private_key = {'n': self.n, 'g': self.g, 'lam': self.lam}
def generate_keys(bit_length): # Make an RSA modulus n. p = find_random_prime(bit_length / 2) while True: q = find_random_prime(bit_length / 2) if p <> q: break n = p * q nsq = n * n # Calculate Carmichael's function. lm = gmpy.lcm(p - 1, q - 1) # Generate a generator g in B. while True: g = rand.randint(1, long(nsq)) if gmpy.gcd(L(pow(g, lm, nsq), n), n) == 1: break return {'n': n, 'g': g}, {'n': n, 'g': g, 'lm': lm}
def generate_keys(bit_length): # Make an RSA modulus n. p = find_random_prime(bit_length/2) while True: q = find_random_prime(bit_length/2) if p<>q: break n = p*q nsq = n*n # Calculate Carmichael's function. lm = gmpy.lcm(p-1, q-1) # Generate a generator g in B. while True: g = rand.randint(1, long(nsq)) if gmpy.gcd(L(pow(g, lm, nsq), n), n) == 1: break return {'n':n, 'g': g}, {'n': n, 'g': g, 'lm': lm}
def is_prime_ss(n,s): #n,s prirozena, n>3 liche ''' return (rounds, res): - rounds is -1 if it passed all tests (ie: probably prime) ''' for i in xrange(0, s): # 0,1,...,s-1 a = random.randint(2,n-2) #nah. c. mezi 2 a n-2 if gmpy.gcd(a,n) != 1: return (i, 0) #je slozene p = pow(a,(n-1)/2,n) if p == n-1: p = -1 if not gmpy.jacobi(a,n) == p: return (i, 0) #je slozene return (-1, 1) #n proslo testem
def make_frac(n, d): a = n b = d % n x = 0 y = 1 lastx = 1 lasty = 0 nn = n.numdigits(2) stop = gmpy.mpz(1) << (nn / 2) while b > stop: q = a / b r = a % b a = b b = r (x, lastx) = (lastx - q * x, x) (y, lasty) = (lasty - q * y, y) (a, b) = (b, y % n) if gmpy.gcd(a, b) != 1: return (None, None) else: return (a, b)
def beal_parallel(max_base, max_power, queue): table = {} for i in xrange(1, max_base): for r in xrange(3, max_power): zr = long(i) ** r table[zr] = r (m, n) = queue.get() while ((m, n) <> (None, None)): print '(%d, %d)' % (m, n) powx, powy = initial_data(max_base, m, n) for x in xrange(1, max_base): powx_tmp = powx[x] for y in xrange(1, x): if gcd(x,y) > 1: continue sum = powx_tmp + powy[y] zr = table.get(sum) if zr: print "Building Report... Possible Find" report(x, m, y, n, nth_root(sum, zr), zr) (m, n) = queue.get()
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 = range(number_of_primes) prime = mpz(2) p1 = get_points(p1, n) if not isinstance(p1, list): return p1 for _ in xrange(int(log_mo / LOG_2)): p1 = double(p1, n) if not isinstance(p1, list): return p1 for i in xrange(1, det_bound): prime = (i << 1) + 1 if isprime(prime): for _ in xrange(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 xrange(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 xrange(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 xrange(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 xrange(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 xrange(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(big_multiple - small_jump_2) while prime_up < big_multiple + small_jump_2: s = small_multiples[abs(int(prime_up) - big_multiple)] for j in xrange(ncurves): product *= pgiant_step[j][0] - s[j] product %= n prime_up = next_prime(prime_up) for i in xrange(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 == None: return pmed_step_up while prime_up < center_up + small_jump_2: s = small_multiples[abs(int(prime_up) - center_up)] for j in xrange(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 xrange(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
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 /= 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 xrange(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 xrange(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 xrange(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 primefac(n, trial_limit=1000, rho_rounds=42000, verbose=False, methods=(pollardRho_brent, pollard_pm1, williams_pp1, ecm, mpqs)): # Obtains a complete factorization of n, yielding the prime factors as they are obtained. # If the user explicitly specifies a splitting method, use that method. Otherwise, # 1. Pull out small factors with trial division. # TODO: a few rounds of Fermat's method? # 2. Do a few rounds of Pollard's Rho algorithm. # TODO: a few rounds of ECM by itself? # TODO: a certain amount of P-1? # 3. Launch multifactor on the remainder. Multifactor has enough overhead that we want to be fairly sure that rho isn't # likely to yield new factors soon. The default value of rho_rounds=42000 seems good for that but is probably overkill. if n < 2: return if isprime(n): yield n; return factors, nroot = [], isqrt(n) for p in primegen(): # Note that we remove factors of 2 whether the user wants to or not. if n%p == 0: while n%p == 0: yield p n /= p nroot = isqrt(n) if isprime(n): yield n return if p > nroot: if n != 1: yield n return if p >= trial_limit: break if isprime(n): yield n; return if rho_rounds == "inf": factors = [n] while len(factors) != 0: n = min(factors) factors.remove(n) f = pollardRho_brent(n) if isprime(f): yield f else: factors.append(f) n /= f if isprime(n): yield n else: factors.append(n) return factors, difficult = [n], [] while len(factors) != 0: rhocount = 0 n = factors.pop() try: g = n while g == n: x, c, g = randrange(1, n), randrange(1, n), 1 y = x while g==1: if rhocount >= rho_rounds: raise Exception rhocount += 1 x = (x**2 + c) % n y = (y**2 + c) % n y = (y**2 + c) % n g = gcd(x-y, n) # We now have a nontrivial factor g of n. If we took too long to get here, we're actually at the except statement. if isprime(g): yield g else: factors.append(g) n /= g if isprime(n): yield n else: factors.append(n) except Exception: difficult.append(n) # Factoring n took too long. We'll have multifactor chug on it. factors = difficult while len(factors) != 0: n = min(factors) factors.remove(n) f = multifactor(n, methods=methods, verbose=verbose) if isprime(f): yield f else: factors.append(f) n /= f if isprime(n): yield n else: factors.append(n)
#!/usr/bin/env python2.6 from time import time from gmpy import gcd # much faster than homecoded or fractions.gcd() start = time() # Section 1: preliminary definitions p = 1009; pm1 = p - 1 q = 3643; qm1 = q - 1 n = p * q phi = pm1 * qm1 # Section 2: building our list of usable e values, as an iterator object es = (e for e in xrange(1, phi, 2) if gcd(e, phi) == 1) # Section 3: building a dict of # unconcealed messages n_unc = {} for e in es: u = (1 + gcd(e - 1, pm1)) * (1 + gcd(e - 1, qm1)) if u in n_unc: n_unc[u].append(e) else: n_unc[u] = [e] # Section 4: printing sum of es that give min # unc. messages m = min(n_unc.iterkeys()) print(sum(n_unc[m])) print(time() - start)
def report(x, m, y, n): x, y = map(long, (x, y)) if (min(x, y) > 0 and min(m, n) > 2 ): if gcd(x,y) == 1: printing('We might have a solution!! Contact bealstreasure.com for details: %d ^ %d + %d ^ %d' % ( x, m, y, n)) f = urllib.urlopen("http://bealstreasure.com/members/savework.php?&result=true&x=" + str(x) + "&m=" + str(m) + "&y=" + str(y) + "&n=" + str(n)).read()
common_digits = True n.remove(nd) d.remove(nd) if not common_digits: return False n_number = int( "".join( [ c for c in n ] ) ) d_number = int( "".join( [ c for c in d ] ) ) if d_number == 0: return False return True if float( n_number ) / float( d_number ) == ratio else False if __name__ == "__main__": numers = [] denoms = [] for numer in range(10,100): for denom in range(numer+1,100): if badfrac( numer, denom ): numers.append(numer) denoms.append(denom) numer = reduce( mul, numers ) denom = reduce( mul, denoms ) divisor = gcd( numer, denom ) print( denom / divisor )
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # You can contact me at [email protected] # Visit my wiki at http://blog.san-ss.com.ar ######################################################################## import gmpy if __name__ == '__main__': p = 1009 q = 3643 n = p * q phi_n = n - p - q + 1 result = 0 min_res = 9999999999999 for e in range(1, phi_n): if gmpy.gcd(e, phi_n) != 1: continue num_unconcealed = (gmpy.gcd(e-1, p-1) + 1) * (gmpy.gcd(e-1, q-1) + 1) if num_unconcealed < min_res: min_res = num_unconcealed result = e elif num_unconcealed == min_res: result += e print("The result is: {0}".format(result))
from Crypto.Util.number import * import gmpy n = 0x7fe8cafec59886e9318830f33747cafd200588406e7c42741859e15994ab62410438991ab5d9fc94f386219e3c27d6ffc73754f791e7b2c565611f8fe5054dd132b8c4f3eadcf1180cd8f2a3cc756b06996f2d5b67c390adcba9d444697b13d12b2badfc3c7d5459df16a047ca25f4d18570cd6fa727aed46394576cfdb56b41 e = 0x10001 c = 0x5233da71cc1dc1c5f21039f51eb51c80657e1af217d563aa25a8104a4e84a42379040ecdfdd5afa191156ccb40b6f188f4ad96c58922428c4c0bc17fd5384456853e139afde40c3f95988879629297f48d0efa6b335716a4c24bfee36f714d34a4e810a9689e93a0af8502528844ae578100b0188a2790518c695c095c9d677b m = bytes_to_long(bytes.fromhex("372f0e88f6f7189da7c06ed49e87e0664b988ecbee583586dfd1c6af99bf20345ae7442012c6807b3493d8936f5b48e553f614754deb3da6230fa1e16a8d5953a94c886699fc2bf409556264d5dced76a1780a90fd22f3701fdbcb183ddab4046affdc4dc6379090f79f4cd50673b24d0b08458cdbe509d60a4ad88a7b4e2921")) r = e-1 p = gmpy.gcd(pow(m, r//2, n) - 1, n) q = gmpy.gcd(pow(m, r//2, n) + 1, n) def factor(_m,_r,_n): for i in range(2,1000): if _r%i == 0: t = pow(_m,_r//i,_n) if gmpy.gcd(t-1,_n) != 1 and gmpy.gcd(t-1,_n) != _n: p = gmpy.gcd(t-1,_n) q = _n//gmpy.gcd(t-1,_n) break return p,q p, q = factor(m , e-1, n) phi = (p-1)*(q-1) d = inverse(e, phi) flag = long_to_bytes(pow(c, d, n)).decode() print (flag)
def report(x, m, y, n, z, r): x, y, z = map(long, (x, y, z)) if (min(x, y, z) > 0 and min(m, n, r) > 2 ): if (x ** m + y ** n == z ** r): if gcd(x,y) == gcd(x,z) == gcd(y, z) == 1: print 'Yay!!!: %d ^ %d + %d ^ %d = %d ^ %d = %s' % ( x, m, y, n, z, r, z**r)
def try_decrypt(k): for c in range(5): x = decrypt(k, open('ciphertext-{}.bin'.format(c+1)).read()) if x is not None: plaintexts[c] = x print "Got plaintext:", x def load_key(n): return RSA.importKey(open('key-{}.pem'.format(n)).read()) print "Stage 1 - GCD" for i in range(10): k1 = load_key(i) for j in range(i+1, 10): k2 = load_key(j) g = gmpy.gcd(k1.n, k2.n) if g != 1: p = long(g) q = long(k1.n / p) phi = (p-1) * (q-1) keys[i] = RSA.construct((k1.n, k1.e, long(gmpy.invert(k1.e, phi)), p, q)) try_decrypt(keys[i]) q = long(k2.n / p) phi = (p-1) * (q-1) keys[j] = RSA.construct((k2.n, k2.e, long(gmpy.invert(k2.e, phi)), p, q)) try_decrypt(keys[j]) print "Stage 2 - Wiener" sys.setrecursionlimit(2000)