import primefac import gmpy from Crypto.PublicKey import RSA try: spacer = "-" * 64 pub_input = argv[1] raw_key = file(pub_input, 'r').read() pub_key = RSA.importKey("""{0}""".format(raw_key)) n = long((pub_key.n)) print spacer print "N: {0}".format(n) e = long((pub_key.e)) print spacer print "E: {0}".format(e) print spacer pnq = list(primefac.primefac(n)) p = str(pnq[0]).strip('mqz(L)') q = str(pnq[1]).strip('mqz(L)') print "P: {0}".format(p) print spacer print "Q: {0}".format(q) print spacer d = long(gmpy.invert(e,(int(p)-1)*(int(q)-1))) print "D: {0}".format(d) print spacer key = RSA.construct((n,e,d)) print key.exportKey() except IndexError: print "RSA NED reconstruction attack" print "{0} pub-key.pem".format(argv[0]) exit()
def main(): print 'starting {}'.format(__file__.split('/')[-1]) startTime = time.time() # for i in range(1, 21): # print i, set(primefac.primefac(i)) GOAL = 4 numInARow = 0 i = 0 while True: i += 1 if i % 1e5 == 0: print i distinctFactors = set(primefac.primefac(i)) if len(distinctFactors) == GOAL: numInARow += 1 if numInARow >= GOAL: firstInStreak = i - numInARow + 1 print 'RESULT: {} - {}'.format(firstInStreak, i) for j in range(firstInStreak, i + 1): print j, set(primefac.primefac(j)) break else: numInARow = 0 elapsedTime = time.time() - startTime print 'elapsedTime: {:.2f} s'.format(elapsedTime)
def excellent(k): """Generate all excellent numbers of size 2k""" A = 10**k; N = A*A-1 factors1 = list(primefac.primefac(A-1)) factors2 = list(primefac.primefac(A+1)) d = divisors(sorted(factors1+factors2)) for i in d: if i*i > N: continue j = N//i x,y = (j+i)//2, (j-i)//2 a,b = (x-A)//2, (y+1)//2 if A//10 <= a < A and 0 <= b < A: n = a*A+b assert(n == b*b-a*a) # Check our logic yield n
def isUgly(self, num): fac_list = [2, 3, 5] # Is the number positive if num > 0: # 1 is typically treated as an ugly number. if num == 1: return True else: # Get prime factors of the num pfactors = list(primefac.primefac(num)) # Remove any duplicate factors such as [2, 2] for num = 4 pfactors = list(set(pfactors)) # Remove 2, 3, 5 and check if the list has # any other element left # If yes then return True for item in fac_list: if item in pfactors: print(str(item) + 'is a factor') pfactors.remove(item) if len(pfactors) == 0: print('This is an ugly number') return True return False
def primefac(self, primefac_timeout=45): # this attack rely on primefac try: from primefac import primefac except ImportError: if self.args.verbose: print("[!] Warning: primefac attack module missing") return # use primefac try: with timeout(seconds=primefac_timeout): result = list( primefac(self.pub_key.n, timeout=primefac_timeout)) except FactorizationError: return if len(result) == 2: self.pub_key.p = int(result[0]) self.pub_key.q = int(result[1]) self.priv_key = PrivateKey(int(self.pub_key.p), int(self.pub_key.q), int(self.pub_key.e), int(self.pub_key.n)) return
def prime_factor(n): """ 找出两个素因子p和q,p*q=n :param n: :return: """ # 这里返回的是所有的质因子 try: r = primefac.primefac(n) found, p, q = False, 0, 0 for i, x in enumerate(r): print(x) if i >= 2: return False, 0, 0 elif i == 0: p = x elif i == 1: q = x found = True print('p: %s, q: %s' % (p, q)) return found, p, q except Exception as e: print(e) pass return False, 0, 0
def sumfactors(base): factors = list(primefac.primefac(base)) total = 1 for i in set(factors): count = factors.count(i) total *= (i**(count + 1) - 1) / (i - 1) return total
def do_factor_stuff(n_old, recursion=0): i = 0 if n_old > 10**8: return print("n_old: {}".format(n_old)) if not n_old in n_map: n_map[n_old] = [] factors = list(primefac.primefac(n_old)) if len(factors) == 1: n_new = factors[0] print("finished here!") if not n_new in p_map: p_map[n_new] = 0 return else: permutation_table = get_permutation_table(len(factors)) # permutation_table = get_permutation_table(len(factors))[:3] factors_arr_str = np.array(list(map(str, factors))) lst = n_map[n_old] for row in permutation_table: n_new = int("".join(factors_arr_str[row])) if not n_new in lst: lst.append(n_new) if not n_new in n_map and recursion < 21: do_factor_stuff(n_new, recursion + 1)
def main(): # input via readline method t = (int)(stdin.readline()) stdout.write(str(t) + "\n\n") for x in xrange(1, t + 1): s = stdin.readline() n = s.split()[0] l = s.split()[1] arr = [int(x) for x in stdin.readline().split()] aux = 10**100 index = 0 count = 0 for x in arr: if x < aux: index = count aux = x count += 1 stdout.write(str(index) + "\n") stdout.write(str(arr[index]) + "\n") stdout.write(str(aux) + "\n") stdout.write(str(largest_prime_factor(aux)) + "\n") factors = list(primefac.primefac(aux)) print '\n'.join(map(str, factors)) stdout.write("\n\n")
def factorise(number: int): """Factorise a number to avoid too large a downsample factor Parameters ---------- number : int The number to factorise Returns ------- List[int] The downsampling factors to use Notes ----- There's a few pathological cases here that are being ignored. For example, what if the downsample factor is the product of two primes greater than 13. """ import primefac factors = list(primefac.primefac(number)) downsamples = [] val = 1 for f in factors: test = val * f if test > 13: downsamples.append(val) val = 1 val = val * f # logic: on the last value of f, val*f is tested # if this is greater than 13, the previous val is added, which leaves one factor leftover # if not greater than 13, then this is not added either # so append the last value. the only situation in which this fails is the last factor itself is over 13. downsamples.append(val) return downsamples
def main(): input = getArgs() a = 20151125 b = 252533 n = 33554393 r = int( input[0].split()[15].strip(',') ) c = int( input[0].split()[17].strip('.') ) # entries are in the form a * b^k (mod n), where k is as follows: # (the grid entries follow the triangular numbers formula, with some # column shifting and a final "- 1" because the first entry is not # multiplied by b) k = ( (r+c-2)*(r+c-1)/2 + c ) - 1 print "k=",k # break k up into prime factors kf = [ i for i in primefac.primefac(k) ] print "k factors into",kf sub = modex(b,kf[0],n) for i in range(1,len(kf)): sub = modex(sub, kf[i], n) print "sub-product through f[%d]" % i,sub print "a * b ^ k = ",a * sub % n
def quadsieve(n): for i in range(2, floor(log2(n))): if n % i == 0: return i, n // i b = 10000 t = pi(b) print("pi(b):", t) count = 0 testnum = int(mpz(n).root(2)[0]) smoothnums = [] smallprimes = set([]) while count <= t: if bsmooth(testnum, b): smoothnums.append(testnum) smallprimes = smallprimes.union(set(primefac(testnum))) count += 1 testnum += 1 smallprimes = sorted(list(smallprimes)) rowlen = len(smallprimes) numnums = len(smoothnums) print((numnums, rowlen)) XOR = lambda x, y: x ^ y AND = lambda x, y: x & y DIV = lambda x, y: x mat = GenericMatrix(size=(numnums, rowlen), zeroElement=0, identityElement=1, add=XOR, mul=AND, sub=XOR, div=DIV) rowcount = 0 for i in smoothnums: # print(i) factor = list(primefac(i)) newrow = [] for p in smallprimes: newrow.append(factor.count(p) % 2) mat.SetRow(rowcount, newrow) rowcount += 1 b = [0] * numnums x = mat.LowerGaussianElim() print(x) return n, n
def phi(n): """Computes the function phi of euler of n""" factorization = Counter(primefac.primefac(n)) ans = 1 for p, e, in factorization.iteritems(): ans *= (p-1) * p**(e-1) return ans
def phi(n): """Computes the function phi of euler of n""" factorization = Counter(primefac.primefac(n)) ans = 1 for p, e, in factorization.iteritems(): ans *= (p - 1) * p**(e - 1) return ans
def is_jamcoin(string): ret = [] for b in range(2, 11): x = int(string, b) factor = primefac.primefac(x).next() if factor == x: #prime return None ret.append(str(factor)) return (string, ret)
def order(g, n): """Smallest k>=0 such that g^k===1(%n)""" phi_n = phi(n) factorization = Counter(primefac.primefac(phi_n)) ans = 1 for p, e in factorization.iteritems(): ans *= pow(p, e-max([k for k in range(e + 1) if fast_exponentiation(g, phi_n/p**k, n) == 1])) return ans
def isprime(num, base): n = int(num, base) p = primefac.primefac(n) data = 1 try: data = p.next() p.next() except: return True, 1 return False, data
def phi(x): """ Implementation of Euler's Totient function """ fac = Counter(list(primefac(x))) result = 1 for factor in fac: result *= (factor-1) * (factor**(fac[factor]-1)) return result
def is_valid_semiprime(num: str) -> bool: try: n = int(num) d = primefac(n) try: return next(d) * next(d) == n except StopIteration: return False except ValueError: return False
def findNums(pubKey): n = pubKey[1] #for i in range(3,int(math.floor(n/3)+1)): #print i, n # for j in range(3, int(math.floor(n/3)+1)): # if i * j == n and isPrime(i) and isPrime(j): # return [i, j] nums = list(primefac.primefac(n)) nums[0] = int(nums[0]) nums[1] = int(nums[1]) return nums
def getnumbers(base): factors = list(primefac.primefac(base)) output = set() if base <= 50: output.add(1) for r in range(1, len(factors) + 1): for numbers in itertools.combinations(factors, r): result = functools.reduce(operator.mul, numbers) if base / result <= 50: output.add(result) return list(output)
def is_valid_powerful_number(num: str) -> bool: try: n = int(num) unique_factors = set(f for f in primefac(n)) for p in unique_factors: if n % (p * p) != 0: return False return True except ValueError: return False
def pollard(a, N): for j in range(2, 100): a = powerMod(a, j) - 1 d = math.gcd(a, N) #print("at %d! a and d are: %d %d "%(j,a,d)) if (d > 1 and d < N): q = N // d #print("aha! at %d! I found the factors %d and %d "%(j,d,q)) d = d - 1 pfactors = list(primefac.primefac(d - 1)) print("the prime factors of " + str(d - 1) + " are: ") print(pfactors) q = q - 1 qfactors = list(primefac.primefac(q - 1)) print("the prime factors of " + str(q - 1) + " are: ") print(qfactors) return True
def decode(token): token = to_number(b58decode(token)) currencies = [] factors = sorted(list(primefac.primefac(token))) for order, p in enumerate(gen_primes()): if p in factors: currencies.append(get_currency_by_order(order)) if len(factors) == len(currencies): break return sorted(currencies)
def order(g, n): """Smallest k>=0 such that g^k===1(%n)""" phi_n = phi(n) factorization = Counter(primefac.primefac(phi_n)) ans = 1 for p, e in factorization.iteritems(): ans *= pow( p, e - max([ k for k in range(e + 1) if fast_exponentiation(g, phi_n / p**k, n) == 1 ])) return ans
def gen(n): factors = list(primefac(n - 1)) a = factors[0] b = 1 for f in factors[1:]: if gcd(f, a) != 1: a *= f else: b *= f if b > a: return (b, a) return (a, b)
def is_jam(int_input): str_input = bin(int_input)[2::] output = str_input for i in range(2, 11): integer = int(str_input, i) if (is_probable_prime(integer)): return False temp = integer factor = primefac.primefac(integer).next() output += " " + str(factor) print output outfile.write(output + "\n") return True
def prime_factors(n): """Determina os fatores primos de um número Com o auxílio do módulo primefac gera-se os fatores primos do número passado como argumento, onde os fatores primos são os números primos que dividem o argumento de maneira exata Args: n: número do qual sera determinado os fatores primos Returns: Uma lista com os fatores primos """ return list(pf.primefac(n))
def factors(value): if value == 1: return [] else: # n = 2 # factors = [] # while value != 1: # if value % n == 0: # factors.append(n) # value = value / n # else: # n += 1 # return factors return list(primefac.primefac(value))
def get(self): try: self.set_header("Content-Type", "text/plain") composite = int(self.get_argument('composite', default="9123456789012345678901456780")) + random.randint(1, 10000) # print composite primes = [str(p) for p in primefac(composite)] self.write("%d ="%composite) for p in primes: self.write(" * ".join(primes)) self.write("\n") except ValueError as ex: self.set_status(400, "Parameter composite not valid") self.write("This is not a number: %s"%self.get_argument('composite', default="0"))
def test_q8(): print('Q8: ==========================') n = 25735664145190389285057703686192800899705919152576441463391134729007771965919846923127428578522061398506987280139163802365132867371555016059630770918319052361574038129434461641589247193942274761931612037853509472630757167158051628233272586365739584359583565563288057330271262509882524468563142934008187343454761865753388775613752888169560816991 e = 65537 c = 23200031227144944397028769497729355064014424828416581750556774525397602689849699109251451304105581128127861174157385537017217940510862046678344757372167221370257932798005668453184830518816316065490772921371044886948724143286659666444040735840140874503594062801406605487511573529273237146181728489574537740324522752694504147671560362550290749631 m = 'JDIS-{RSA_B3-C4R3FUL-86123112}' # Then, decrpyt ps = list(primefac.primefac(n)) phi = 1 for i in ps: phi *= (i - 1) d = getModInverse(e, phi) m_p = pow(c, d, n) assert m == bytearray.fromhex(format(m_p, 'x')).decode(), (m, m_p)
def Mapsize(n): factors = list(primefac.primefac(n)) #print factors if len(factors) == 1: return 1, n elif len(factors) == 2: return factors[0], factors[1] else: x = int(math.floor(len(factors) / 2)) p1 = 1 p2 = 1 p3 = 1 for i in range(x + 1): p1 = p1 * factors[i] for j in range(x + 1, len(factors)): p2 = p2 * factors[j] return p1, p2
def get_combinations(order): factors = list(primefac(order)) factor_set = set(factors) factors_listed = [] for factor in factor_set: current_factor_combos = [] factor_count = factors.count(factor) for partition in accel_asc(factor_count): current_factor_combos.append( [factor**value for value in partition]) factors_listed.append(current_factor_combos) all_combos = product(*factors_listed) combinations_list = [] for combo in all_combos: flattened = [item for sublist in combo for item in sublist] combinations_list.append(flattened) return combinations_list
def f(s, e): while s < e: if s % 2 == 0: s += 1 continue st = '{0:b}'.format(s) ll = [] for b in range(2, 11): cur = int(st, b) if primefac.isprime(cur): break ll.append(cur) else: for i in xrange(len(ll)): ll[i] = primefac.primefac(ll[i]).next() return (s, ll) s += 1
def factorise(number): import primefac factors = list(primefac.primefac(number)) downsamples = [] # there's a few pathological cases here that are being ignored # what if the downsample factor is the product of two primes greater than 13 # let's ignore this situation for the time being val = 1 for f in factors: test = val * f if test > 13: downsamples.append(val) val = 1 val = val * f # logic: on the last value of f, val*f is tested # if this is greater than 13, the previous val is added, which leaves one factor leftover # if not greater than 13, then this is not added either # so append the last value. the only situation in which this fails is the last factor itself is over 13. downsamples.append(val) return downsamples
def decode_currency_support_token(token): token = to_number(b58decode(token)) currencies = [] print("factoring %s" % token) t0 = datetime.datetime.now() if is_py2: import primefac factors = sorted(list(primefac.primefac(token))) else: factors = find_factors() print("factors are %s" % factors) print("factoring took %s" % (datetime.datetime.now() - t0)) for order, p in enumerate(gen_primes()): if p in factors: currencies.append(get_currency_by_order(order)) if len(factors) == len(currencies): break return sorted(currencies)
def primefac(self, primefac_timeout=60): # this attack rely on primefac try: from primefac import primefac except ImportError: if self.args.verbose: print("[!] Warning: primefac attack module missing") return # use primefac try: with timeout(seconds=primefac_timeout): result = list(primefac(self.pub_key.n)) except FactorizationError: return if len(result) == 2: self.pub_key.p = int(result[0]) self.pub_key.q = int(result[1]) self.priv_key = PrivateKey(int(self.pub_key.p), int(self.pub_key.q), int(self.pub_key.e), int(self.pub_key.n)) return
def multiply_by(self,f): self.numerator.update(primefac.primefac(f))
def divide_by(self,d): self.denominator.update(primefac.primefac(d))
#!python """https://matthewarcus.wordpress.com/2016/01/16/excellent-numbers/""" """https://pypi.python.org/pypi/primefac""" import primefac for n in range(2,100): nines = 10 ** n - 1 print "%d:" % (n), for f in primefac.primefac(nines): print " " + str(f), print " | ", nines