def main(argv): n = 0 e = 0 try: opts, args = getopt.getopt(argv, "n:e:", []) except getopt.GetoptError: print 'blerg' sys.exit(2) for opt, arg in opts: if opt in ("-n"): n = int(arg, 16) if opt in ("-e"): e = int(arg) if n == 0: print "Enter an N" exit(1) if e == 0: print "Enter an e" exit(2) #print "Factoring " + str(n) pq = FactorDB(n) pqlist = pq.get_factor_list() phi = (pqlist[0] - 1) * (pqlist[1] - 1) d = modInv(e, phi)[1] #print d rsa = RSA(pqlist[0], pqlist[1], e) data = rsa.to_pem() fp = open("./private.key", 'wb') fp.write(data) fp.close() exit(0)
def crack(solver): a = FactorDB(solver.datas["n"][-1]) a.connect() b = a.get_factor_list() if (len(b) == 2): solver.addp(b[0]) solver.addq(b[1])
def decrypt(e, c, n) -> mpz: f = FactorDB(n) f.connect() p, q = f.get_factor_list() phi = gmpy2.mul(p - 1, q - 1) d = gmpy2.invert(e, phi) return gmpy2.powmod(c, d, n)
def crack(solver): n = solver.datas["n"][-1] e = solver.datas["e"][-1] a = FactorDB(n) a.connect() if (a.get_status() == "P"): d = libnum.modular.invmod(e, n - 1) solver.addd(d)
def test_factordb_api_16(self): factordb = FactorDB(16) factordb.connect() self.__check_testcase(factordb, { 'id': '2', 'status': 'FF', 'factors': [2, 2, 2, 2] })
def test_factordb_api_1(self): factordb = FactorDB(1) factordb.connect() self.__check_testcase(factordb, { 'id': -1, 'status': "Unit", 'factors': [] })
def factorize_by_factordb(n): sc = FactorDB(n) sc.connect() raw_factorized = sc.get_factor_from_api() ret = [] for factor in raw_factorized: s_base, exponent = factor ret.append((int(s_base), exponent)) return ret
def factordb(n): try: from factordb.factordb import FactorDB if n < 2**128: return None f = FactorDB(n) if f.get_status() in ['FF', 'CF']: return int(f.get_factor_list()[0]) except ImportError: return None
def test_factordb_api_prime(self): factordb = FactorDB(7) factordb.connect() self.__check_testcase(factordb, { 'id': '7', 'status': 'P', 'factors': [7] }) self.assertTrue(factordb.is_prime())
def decWithSpec(self, number, spectrum, base=10): spectrum = spectrum.toVariant() for i in range(len(spectrum)): spectrum[i] = int(spectrum[i]) totalFound = [] f = FactorDB(number) connection = f.connect() l = f.get_factor_list() for p in l: spec = pseudoSpectrum(p, base) if spec == spectrum: totalFound.append(shortVersion(str(p))) return totalFound
def check_fdb(mod): f = FactorDB(mod) try: assert "200" in str(f.connect()) stat = f.get_status() if (stat == "CF"): print("\nWarning : this modulus is not safe, factors are known") elif stat == "FF": factors = f.get_factor_list() print( "\n Warning : this modulus has been fully factorised, factors known : \n" ) print(factors) else: print("\nNo factors known") except AssertionError: print("Unable to connect to FactorDB")
async def factordb(self, ctx,string): byted_str = int(string) f = FactorDB(byted_str) f.get_factor_list() f.connect() out = f.get_factor_list() await ctx.send(out)
def test_factordb_api_large_composite_number(self): """ Large composite number tests from RSA 768 challenges """ p = int("3347807169895689878604416984821269081770479498371376856891243" "1388982883793878002287614711652531743087737814467999489") q = int("3674604366679959042824463379962795263227915816434308764267603" "2283815739666511279233373417143396810270092798736308917") factordb = FactorDB(p * q) factordb.connect() self.__check_testcase(factordb, { 'id': '1100000000193442616', 'status': 'FF', 'factors': [p, q] } )
def basic_factor(basic_factor_attack_params): e = basic_factor_attack_params['e'] n = basic_factor_attack_params['n'] try: f_list = FactorDB(n).get_factor_list() except: return -1 if len(f_list) == 2: phi = (f_list[0] - 1) * (f_list[1] - 1) d = gmpy.invert(e, phi) return d return -1
def factor_n(n): from factordb.factordb import FactorDB f = FactorDB(n) f.connect() if f.get_status() == "FF": factors = f.get_factor_list() return factors
def isCyclic(self): import importlib sympyLib = importlib.find_loader('sympy') if sympyLib is not None: from sympy.ntheory import primefactors primesList = primefactors(self._den) else: from factordb.factordb import FactorDB f = FactorDB(self._den) connection = f.connect() primesList = f.get_factor_list() isDenPrime = len(primesList) == 1 self._isCyclic = False if isDenPrime and self._num < self._den and self._period != 0: self._isCyclic = True cycleList = [] spectrumsSet = set() for n in range(1, self._den): number = Rational() number.calc(n, self._den, self._scaleOfNotation) cycleList.append(number) spectrumsSet.add(number.spectrumString()) if len(spectrumsSet) == (self._den - 1) / self._period: self._amountOfCycles = len(spectrumsSet) self._vertTables = [] for i in range(self._period): singleVerTab = [] for j in range(1, self._den): singleVerTab.append(int(cycleList[j - 1].digits()[i + 1])) self._vertTables.append(singleVerTab) self._multiplyShiftList = [0] protoPeriod = cycleList[0].digits(part='period') for i in range(2, self._den): firstPeriodDigit = cycleList[i - 1].digits(part='period')[0] for index, digit in enumerate(protoPeriod): if digit == firstPeriodDigit: self._multiplyShiftList.append(index) cyclicNumber = int( (self._scaleOfNotation**self._period) * (1.0 / self._den)) return self._isCyclic
def process(self, X): try: f = FactorDB(X) f.connect() if f.get_status() in ['FF', 'CF']: return sage.Integer(f.get_factor_list()[0]) except ImportError: return None
def cyclicPairNumber(self): if self._isCyclic: repunitString = '9' * self._period periodBorder = gmpy2.mpz(repunitString) import importlib sympyLib = importlib.find_loader('sympy') if sympyLib is not None: from sympy.ntheory import primefactors primes = primefactors(periodBorder) else: from factordb.factordb import FactorDB f = FactorDB(periodBorder) connection = f.connect() primes = f.get_factor_list() primesSet = set(primes) equalPeriods = [] for primeNumber in primesSet: pass rational = Rational() #slow.. TODO rational.calc(1, primeNumber, self._scaleOfNotation) if rational.getPeriod() == self._period: equalPeriods.append(primeNumber) return equalPeriods
def factor(n, e, c): print("[*] Try factor", n) f = FactorDB(n) print("[*] Try connect") if f.connect().status_code != 200: print("[x] Connect Failed") return 0 lst = f.get_factor_list() if len(lst) == 1: print("[x] Factor Failed") return 0 print("[*] the factor result:", lst) lst = set(lst) tn = n for i in lst: tn = tn // i * (i - 1) d = invert(e, tn) print("[*] Maybe success") print("[!] flag:", long_to_bytes(pow(c, d, n))) return 1
def factordb(n): try: from factordb.factordb import FactorDB if n < 2**128: return None f = FactorDB(n) f.connect() if f.get_status() in ["FF", "CF"]: return int(f.get_factor_list()[0]) except ImportError: return None
def makePrimeStringList(number): strList = [] import importlib sympyLib = importlib.find_loader('sympy') if sympyLib is not None: if len(str(number)) > 30: f = FactorDB(number) connection = f.connect() l = f.get_factor_list() for el in l: strList.append(str(el)) else: from sympy.ntheory import primefactors primes = primefactors(number) for el in primes: strList.append(str(el)) else: f = FactorDB(number) connection = f.connect() l = f.get_factor_list() for el in l: strList.append(str(el)) return strList
import gmpy from pwn import * from Crypto.Util.number import long_to_bytes import binascii from factordb.factordb import FactorDB n = int(open("n", "r").read()) c = int(open("c", "r").read()) e = 65537 f = FactorDB(n) f.connect() arr = f.get_factor_list() phi = 1 for a in arr: phi *= (a - 1) d = gmpy.invert(e, phi) flag = long_to_bytes(pow(c, d, n)).decode() log.success("Flag: {}".format(flag))
# to decrypt simple RSA ciphers # comment from Crypto.Util.number import * from factordb.factordb import FactorDB print("Let's try to decrypt RSA encrypted cipher") n = int(input("ENTER n : ")) e = int(input("ENTER e : ")) c = int(input("ENTER c : ")) f = FactorDB(n) f.get_factor_list() f.connect() result = f.get_factor_list() p = result[0] q = result[1] phi = (p - 1) * (q - 1) d = inverse(e, phi) m = pow(c, d, n) print("The message is :") print(m) print("-" * 70) print("The message after long_to_bytes is :") print(long_to_bytes(m))
def factorize(n): f = FactorDB(n) f.connect() return f.get_factor_list() '''
from Crypto.Util.number import * from functools import reduce from factordb.factordb import FactorDB import gmpy2 enc = 493411990714034701192036868925033382533813449023272468886834417275865894890277610897602010608126211732489729110637453412478527735277532858305194132432995412335314758844973458067236971260497417393244304994147175160121126866274637094642084286422204250530071767179407437175780827344723433812174890560874797281085881372866235919836442489439131953350250339903321616150128653702980111364606793773693115742802148096105255600570826866081538329662788508308910574300106675 pubkey = ( 58899560795422629508383709585815596674993413635981165980320127271644038316448725758306722451998784991954419091526089159750869500335163383766827243981828688851948124591111627934859094536105678156714083380927689539385480719433890644570016706624506640312364077682372260047937960244512523766943378334280751887151, 10035997187541816220681016469393172095726015614633459513695480820099536637633364416223346540578858375371324216891862234038678667156169323844411428795236483 ) n = 591115826490309729652229755684270397434097686987727132849445065006972555773162612455224258285657736679144410500970377961890880097323795620295567282728281205781926398127386353388403223985287571516890214047163630378154565164133069511631420478272985759890740867426338066843463645285144809736210454105484643766386941651135723254162002945871342384329597971199753078727923204118362911548120474585611933295292478563468192801468080852784566136578969407694226961574129933 p2_p3 = gmpy2.div(pubkey[0], pubkey[1]) print('p2_p3 = {}'.format(p2_p3)) f = FactorDB(pubkey[1]) f.connect() p0, p1 = f.get_factor_list() print('p0 = {}'.format(p0)) print('p1 = {}'.format(p1)) ''' Since n=p0**2*p1**2*p2*p3 I need to factorize p2_p3 to determine that value and find mul iverse mod phi(n) of e, however if our plaintext is less than p0**2*p1**2 (or some combination of the base such that e % phi(reduced_n)==1) than I can rewrite enc as enc % reduced_n and try to find inverse multiplicative on phi(reduced_n). ''' phi = gmpy2.mul(gmpy2.mul(p0, p0 - 1), gmpy2.mul(p1, p1 - 1)) e = 65537 d = inverse(e, phi) '''
_sage_const_2 = Integer(2); _sage_const_1 = Integer(1); _sage_const_0 = Integer(0) import OpenSSL.crypto as crypto from factordb.factordb import FactorDB key = open("pubkey.pem","rb").read() message = open("message.txt","rb").read() key = crypto.load_publickey(crypto.FILETYPE_PEM, key) numbers = key.to_cryptography_key().public_numbers() N = numbers.n E = numbers.e C = int(message) f = FactorDB(N) f.connect() if f.get_status() == "FF": factors = f.get_factor_list() if len(factors) != _sage_const_2 : print("invalid N") exit(_sage_const_1 ) P = factors[_sage_const_0 ] Q = factors[_sage_const_1 ] D = xgcd(E,(P - _sage_const_1 ) * (Q - _sage_const_1 ))[_sage_const_1 ] M = pow(C,D,N) print(hex(int(str(M))).replace("L","")[_sage_const_2 :].decode('hex')) else: print("Not fully factored")
#Source: https://github.com/ryosan-470/factordb-pycli?fbclid=IwAR2SYJCiizMXWOvHrmvZqKLTmT0rEhm1Tl7dYcBrJ_oRN8vSXqIxFGrQuB8# #instructions on how to use this tool are on the github def int2string(my_int): return binascii.unhexlify(format(my_int, "x").encode("utf-8")).decode("utf-8") n = 79832181757332818552764610761349592984614744432279135328398999801627880283610900361281249973175805069916210179560506497075132524902086881120372213626641879468491936860976686933630869673826972619938321951599146744807653301076026577949579618331502776303983485566046485431039541708467141408260220098592761245010678592347501894176269580510459729633673468068467144199744563731826362102608811033400887813754780282628099443490170016087838606998017490456601315802448567772411623826281747245660954245413781519794295336197555688543537992197142258053220453757666537840276416475602759374950715283890232230741542737319569819793988431443 e = 65537 ciphertext = 877047627503964563527859854056241853286548710266261291942543955818132370489959838496983429954434494528178229313135354793125902041844995518092695073588272773865176510386504459109444540504995243455296652458363596632448945407597570368304177404561607143991631472612686460090955582314803404185085391881900665937993904325795901688452399415391744151647251408176477627720933717024380735888111455809609800839992904182591275652616244755461341372866557636825262065485442416189938154309976219500988259186981644426083447522183242945513870008042818029602927271842718324310884266107435333212981162347887454715321088536179467180247805306 #f is used in order to find the factors of n. n is p*q, so by factorizing it is possible to find p and q. #once p and q are found then it is possible to find d using the same solution as challenge 6. f = FactorDB(n) f.connect() #I have printed the two factors so I know what they are, after I have printed them out, I have hard coded them in as values. print(f.get_factor_list()) #p and q hard coded into program after found through factorizing n p = 3133337 q = 25478326064937419292200172136399497719081842914528228316455906211693118321971399936004729134841162974144246271486439695786036588117424611881955950996219646807378822278285638261582099108339438949573034101215141156156408742843820048066830863814362379885720395082318462850002901605689761876319151147352730090957556940842144299887394678743607766937828094478336401159449035878306853716216548374273462386508307367713112073004011383418967894930554067582453248981022011922883374442736848045920676341361871231787163441467533076890081721882179369168787287724769642665399992556052144845878600126283968890273067575342061776244939 #phi is equal to p - 1 multiplied by q - 1 phi = (p - 1) * (q - 1) #Mod Inverse Function# def modInverse(a, m):
print('================================\nBase64 Decoded:\n', base64.b64decode(decompressed)) print("\nWe can see it's a message appended with public key") msg1, msg2, pubkey = b64decoded.split(b"\n\n") # the output looks like a RSA key from Crypto.PublicKey import RSA key = RSA.import_key(pubkey) print("Public key is", key.n) print("\nThe hint was to not brute force and it is not a short RSA key so maybe we can lookup its factorization somewhere") print("\nGoogling gives out factordb as a first result and they have a python module, GREAT!") from factordb.factordb import FactorDB f = FactorDB(key.n) f.connect() factor_list = f.get_factor_list() print("\nFactor list from FactorDB:", factor_list) print("\nSo we found p and q") p, q = factor_list d = inverse_mod(key.e, (p - 1)*(q - 1)) print("\nAnd private key is:", d) c = enc.read().strip('\n') m = pow(int(c, 0), d, key.n) print("\nSo the answer is {}".format(m))
for old in modules: if int(gmpy2.gcd(old, params["n"])) != 1: print str(old) + ' ' + str(params["n"]) exit(0) print ' [~] All modules are co-prime' modules.append(params["n"]) # It looks like in some cases, the FactorDB won't factorize a number unless # we first access the web API. requests.get("http://factordb.com/index.php?query={}".format(params["n"])) status = '' if True: f = FactorDB(params["n"]) f.connect() factor_list = f.get_factor_list() status = f.get_status() log.info("Received from FactorDB: {} (status: {})".format( factor_list, status)) if len(factor_list) == 1: continue p, q = factor_list log.info("p: {}".format(p)) log.info("q: {}".format(q)) assert (p * q == params["n"]) ph = (p - 1) * (q - 1)
return [a, b] r = remote("crypto.2021.chall.actf.co", 21600) got_numbers = [] got_factors = [] # Get three random numbers and factorize them for i in range(3): r.recvuntil("[g]? ", drop=True) r.sendline("r") n = int(r.recvline().strip()) f = FactorDB(n) f.connect() assert f.get_status() == "FF", "Number not factored" f = f.get_factor_list() got_numbers.append(n) got_factors.append(f) # Find all possible seed couples possible_second_seeds = [] first_factors = got_factors[0] for p in product([0, 1], repeat=len(first_factors)): first_seeds = [1, 1] for i in range(len(first_factors)):