def init2(self): f = self.length_sq() self.rational = gmpy2.is_square(f.numerator) and gmpy2.is_square(f.denominator) if self.rational: n = int(gmpy2.iroot(f.numerator, 2)[0]) d = int(gmpy2.iroot(f.denominator, 2)[0]) self.length = fractions.Fraction(n, d)
def fermatFactor(n): a = gmpy2.iroot(gmpy2.mpz(n), 2)[0] + 1 b2 = a**2 - n while gmpy2.is_square(b2) is False: a += 1 b2 = a**2 - n return (a - gmpy2.iroot(b2, 2)[0], a + gmpy2.iroot(b2, 2)[0])
def factor_rsa_modulus_split(N): N = mpz(N) A, exact = gmpy2.iroot(24 * N, 2) if not exact: A = A + 1 x, exact = gmpy2.iroot(A * A - 24 * N, 2) if not exact: print "Exact x not found" return None # have to check both positive and negative roots r = check_x(A, x) if r is None: r = check_x(A, -x) # Neither one worked if r is None: print "Cannot find p and q that fit" return None p, q = r if (p * q) != N: print "Found pair %s, %s but they don't produce N" % (str(p), str(q)) return None return p, q
def stage6(c, N): i = 0 while 1: if (gmpy2.iroot(c + i * N, 3)[1] == 1): print i return gmpy2.iroot(c + i * N, 3) i = i + 1
def rev_crow(res, alpha): A = gmpy2.iroot(6 * res, 3)[0] B = gmpy2.iroot((6 * res - A**3) // 3, 2)[0] + alpha z = A - B y = (-6 * res + A**3 + 3 * (B**2) + 2 * B - z - 6) // 6 x = B - y - 1 return (x, y, z)
def smalle(n, c, e=3): m = 0 # res是m for k in range(200000000): if gmpy2.iroot(c + n * k, e)[1] == 1: m = gmpy2.iroot(c + n * k, e)[0] print(k, m) print(libnum.n2s(m)) return m
def fermat(n): a = gmpy2.isqrt(n) + 1 b = a ** 2 - n while not gmpy2.iroot(b, 2)[1]: a += 1 b = a ** 2 - n b = gmpy2.iroot(b, 2)[0] return (a + b, a - b)
def Brute(n, e, c): k = 0 while True: if gmpy.iroot(c + k * n, e)[1] == True: m = gmpy.iroot(c + k * n, 3)[0] print(long_to_bytes(m)) break k += 1
def factorise(n): #n,k=Ncheck(n) a = gmpy2.iroot(n, 2)[0] b = gmpy2.square(a) - n while ((a + b) <= n): if (gmpy2.is_square(b) == True): print(a, b) a = a + 1 b = gmpy2.iroot(gmpy2.square(a) - n, 2)[0]
def hastads(N, e, c): log.info( 'start Hastad attack. If there was no result after a long time. Press ctrl+c to stop, and try other ways.') n = 0 while True: if gmpy2.iroot(c + n * N, e)[1]: log.info('Here are your plain text: \n' + libnum.n2s(gmpy2.iroot(c + n * N, e)[0])) return n += 1
def fermat(n): a = gmpy2.iroot(n, 2)[0]+1 count = 0 while not gmpy2.iroot(a**2 - n, 2)[1]: a += 1 count += 1 if count == 100: return 0, 0 b = gmpy2.iroot(a**2 - n, 2)[0] return a+b, a-b
def fermat(n, verbose=True): a = iroot(n, 2)[0] + 1 b = a * a - n while not iroot(b, 2)[1]: a = a + 1 b = a * a - n b = iroot(b, 2)[0] p = a + b q = a - b return p, q
def main(): pth = fileChoose() with open(pth, "rb") as f: binary = f.read() L = len(binary) wid = None if L % 3 != 0: binary = os.urandom(3 - L % 3) + binary L = len(binary) if iroot(L // 3, 2)[1]: wid = int(iroot(L // 3, 2)[0]) else: wid = int(iroot(L // 3, 2)[0]) + 1 binary = os.urandom(3 * (wid**2 - L // 3)) + binary L = len(binary) assert L % 3 == 0, "Data cannot be RGB raw data" assert L == len(binary), "L must be length of binary" # BITMAPFILEHEADER bfType = b'BM' bfSize = bytes.fromhex(hexLE(L + 0x8A)) bfReserved = bytes.fromhex("00000000") bfOffBits = bytes.fromhex("8A000000") FILEHEADER = bfType + bfSize + bfReserved + bfOffBits # BITMAPINFOHEADER biSize = bytes.fromhex("7C000000") biWidth = bytes.fromhex(hexLE(wid)) # Need to change biHeight = bytes.fromhex(hexLE(wid)) # Need to change biPlanes = bytes.fromhex("0100") biBitCount = bytes.fromhex("1800") biCompression = bytes.fromhex("00000000") biSizeImage = bytes.fromhex(hexLE(L)) biXPelsPerMeter = bytes.fromhex("27000000") biYPelsPerMeter = bytes.fromhex("27000000") biClrUsed = bytes.fromhex("00000000") biClrImportant = bytes.fromhex("00000000") INFOHEADER = biSize + biWidth + biHeight + biPlanes + biBitCount + biCompression + biSizeImage + biXPelsPerMeter + biYPelsPerMeter + biClrUsed + biClrImportant DUMMY = os.urandom(84) npth = pth filename = npth.split("/")[-1] if filename.find(".") == -1: npth = npth + ".bmp" else: filename = '.'.join(filename.split(".")[:-1]) + ".bmp" npth = '/'.join(npth.split("/")[:-1]) + "/" + filename with open(npth, "wb") as f: DATA = FILEHEADER + INFOHEADER + DUMMY + binary f.write(DATA)
def attack_com_mode(n, c1, c2, e1, e2): # g为e1和e2的最大公约数 g, s, t = gmpy2.gcdext(e1, e2) m = pow(c1, s, n) * pow(c2, t, n) % n y, b = gmpy2.iroot(m, g) k = 2 while not b: att_m = m + k * n y, b = gmpy2.iroot(att_m, g) k += 1 return y
def start(n, e, c): res = 0 #print(time.asctime()) for i in range(200000000): if gmpy2.iroot(c + n * i, 3)[1] == 1: res = gmpy2.iroot(c + n * i, 3)[0] #print(i, res) #print(long_to_bytes(res)) #print(time.asctime()) print("Successfully Cracked") break return long_to_bytes(res)
def crack(solver): e = solver.datas["e"][-1] n = solver.datas["n"][-1] for k in range(1, 1000000): if gmpy2.iroot(1 + 4 * e * n * k, 2)[1]: q = int((1 + int(gmpy2.iroot(1 + 4 * e * n * k, 2)[0])) // (2 * e)) solver.addq(q) if n % q == 0: p = n // q solver.addp(p) phin = (p - 1) * (q - 1) d = inverse(e, phin) solver.addd(d) break
def prime_power(x): if gmpy2.is_prime(x): return x, 1 if x == 0 or x == 1: return None, None if not gmpy2.is_power(x): return None, None alpha = 2 root, is_root = gmpy2.iroot(x, alpha) while not (is_root and not gmpy2.is_power(root)): alpha += 1 root, is_root = gmpy2.iroot(x, alpha) if gmpy2.is_prime(root): return root, alpha return None, None
def generate_q7(): print('Q7: ==========================') p = generate_prime_number() q = generate_prime_number() m = generate_prime_number(256) n = p * q e = 3 c = pow(m, e, n) print('Given n, e, c, generate m') # The trick here is that e is so small you can just # get the (cubic root of c) % n to get m gc = gmpy2.mpz(c) gn = gmpy2.mpz(n) ge = gmpy2.mpz(e) root, _ = gmpy2.iroot(gc, ge) m_p = gmpy2.t_mod(root, gn) assert(m_p == m) print('Values') print('n: {}'.format(n)) print('e: {}'.format(e)) print('c: {}'.format(c)) print('Answer') print('m: {}'.format(m))
def crack(solver): n=solver.datas["n"] c=solver.datas["c"] le=len(n) # calc N N = 1 for num in n: N *= num # N1,N2...Nn # NN1 * t1 = 1 (mod n1) NN = [None] * le t = [None] * le x = 0 for i in range(le): NN[i] = int(N / n[i]) t[i] = gmpy2.invert(NN[i],n[i]) x += c[i]*t[i]*NN[i] res = x % N for i in range(2, 65535): num = 0 try: flag = long_to_bytes(gmpy2.iroot(res,i)[0]) for j in flag: if j not in string.printable: num = 1 break if num == 0: print ('e is ' + str(i)) print (flag) except: continue
def crt_recover_plaintext(ciphertext_list): ciphertexts, moduli = zip(*ciphertext_list) assert all_coprime(moduli) modulus_product = 1 for mod in moduli: modulus_product *= mod result_so_far = 0 for ciphertext, modulus in ciphertext_list: # int division to make sure m_s is an integer assert modulus_product % modulus == 0 m_s = modulus_product // modulus result_so_far += ciphertext * m_s * inverse_mod(m_s, modulus) # find the cube root of the result # // we have result_so_far = (m**3) % modulus_product which means m ** 3 = result_so_far + n * modulus_product # // m = cube_root(result_so_far + n * modulus_product) - need to find the n value that makes this equation true # m < n1, m < n2, and m < n3 based on the requirements of RSA, so m ** 3 < n1 * n2 * n3 # modulus_product = n1 * n2 * n3, so m**3 < modulus_product, so cubing won't wrap around the modulus # If cubing doesn't wrap, that means that cube root mod modulus_product = regular cube root # use gmpy for extra precision result_mpz = mpz(result_so_far % modulus_product) root_mpz, exact = iroot(result_mpz, 3) # root should always be exact for reasoning explained in above comment (message cubed should never wrap) assert exact root = int(root_mpz) return num_to_bytes(root)
def hastad_attack_parallel(residue_and_moduli, e, parallel=6, major_chunk_size=1200, minor_chunk_size=120): """ Calculate Hastad broadcast attack using Chinese Remainder Theorem using parallel solver. The more parallel processes you choose, the faster it will run, assuming you have enough CPU cores. The bigger the chunks, the faster it will run, but it will also consume more memory. Memory consumption is maximum once minor chunks start to process, so if you reached this stage without swapping, you should be fine. :param residue_and_moduli: list of pairs (remainder, modulus) :param e: RSA public exponent :param parallel: how many parallel processes to run, best effects with n-1 or n-2, where n is number of cores you have :param major_chunk_size: size of the data split chunk :param minor_chunk_size: size of single multiplication chunk :return: attack result, most likely RSA plaintext if there was enough data """ import gmpy2 print( "With this setup you can recover RSA message only if length was < %f of the average modulus size" % (len(residue_and_moduli) / (e * 1.0))) if major_chunk_size % parallel != 0 or minor_chunk_size % parallel != 0: print( "Keep in mind that it's better to choose chunk size as multiples of parallel processes count" ) crt = solve_crt(residue_and_moduli, parallel, major_chunk_size, minor_chunk_size) solution, _ = gmpy2.iroot(crt, e) return solution
def factor(n): p = int(iroot(n, 2)[0]) while p > 1: if n % p == 0: return p, (n / p) p -= 1 return N, 1
def small_e_msg(key, ciphertexts=None, max_times=100): """If both e and plaintext are small, ciphertext may exceed modulus only a little Args: key(RSAKey): with small e, at least one ciphertext ciphertexts(list) max_times(int): how many times plaintext**e exceeded modulus maximally Returns: list: recovered plaintexts """ ciphertexts = get_mutable_texts(key, ciphertexts) recovered = [] for ciphertext in ciphertexts: log.debug("Find msg for ciphertext {}".format(ciphertext)) times = 0 for k in range(max_times): msg, is_correct = gmpy2.iroot(ciphertext + times, key.e) if is_correct and gmpy2.powmod(msg, key.e, key.n) == ciphertext: msg = int(msg) log.success("Found msg: {}, times=={}".format( i2h(msg), times // key.n)) recovered.append(msg) break times += key.n return recovered
def ch42(): def make_pkcs15(msg, num=1): return b'\x01' + (b'\xff' * num) + b'\x00ASN.1' + as_bytes(msg) def pkcs15_check(padded, msg): pat = b'\x01\xff+\x00ASN.1' + re.escape(as_bytes(msg)) return re.match(pat, as_bytes(padded)) is not None assert_eq(pkcs15_check(make_pkcs15('x'), 'x'), True) assert_eq(pkcs15_check(make_pkcs15('x', 2), 'x'), True) assert_eq(pkcs15_check(make_pkcs15('x', 0), 'x'), False) assert_eq(pkcs15_check(make_pkcs15('x'), 'y'), False) enc, _ = RSA.make_enc_dec_pair(bits=1024, e=3) msg = 'hi mom' msg_pad = make_pkcs15(msg) n = bytes2int(msg_pad) n_upper = n + 1 while True: n3, exact = gmpy2.iroot(n, 3) n3 = int(n3) if not exact: n3 += 1 n33 = n3**3 assert n33 < enc._n if n33 < n_upper: break n <<= 8 n_upper <<= 8 assert_eq(pkcs15_check(int2bytes(enc(n3)), msg), True)
def forgeSign(hash_mes,length): ''' because they not check number of 0xff so we can fake it ,and they just take enough number of hash but not check the character behind the hash(true is no letter more)''' C = b'\x00\x01\xff\xff\x00' + b'ASN_SHA1' + hash_mes while (len(C) != length): C += b'\x00' sign = iroot(bytes_to_long(C),3)[0] + 1 return long_to_bytes(sign)
def decrypt_by_crt(messages, public_key): """ Requires that messages is an array of tuples of the form (ciphertext_i, n_i), where ciphertext_i for each i is the same message message m that is encrypted by m^public_key mod n_i. Attempts an attack based on the Chinese Remainder theorem to compute m^public_key_key mod (n_1 * n_2 * ...). Here the hope is that m^public_key is not large compared to (n_1 * n_2 * ...) so that we can recover the original message by just taking (ciphertext_i - n_i * k)^(1/public_key) where k is fairly small. Of course this attack only works if (ciphertext_i, n_i) are all encryptions of the same original message (with identical padding), encrypted with the same (small) public. Returns None if unable to decrypt the messages. """ print("Attempting decryption using CRT") crt_system = [(bits_to_int(string_to_bits(message[0])), message[1]) for message in messages] crt_solution = solve_crt_system(crt_system) # Recover the original message by taking the public_key root MAX_CRT_ROOT_TRIES = 10 for i in range(MAX_CRT_ROOT_TRIES): root_result = gmpy2.iroot(gmpy2.mpz(crt_solution[0] + crt_solution[1] * i), public_key) if root_result[1]: oaep_padded_plaintext_int = root_result[0] return remove_oaep_from_plaintext(oaep_padded_plaintext_int, crt_system[0][1]) return None
def broadcast_attack(data): def extended_gcd(a, b): x, y = 0, 1 lastx, lasty = 1, 0 while b: a, (q, b) = b, divmod(a, b) x, lastx = lastx - q * x, x y, lasty = lasty - q * y, y return (lastx, lasty, a) def chinese_remainder_theorem(items): N = 1 for i in items: N *= i["n"] result = 0 for i in items: m = N // i["n"] r, s, d = extended_gcd(i["n"], m) if d != 1: N = N / i["n"] continue result += i["c"] * s * m return result % N, N x, n = chinese_remainder_theorem(data) m = gmpy2.iroot(x, 10)[0] return m
def commonmodulo(n, e1, e2, c1, c2): def egcd(a, b): if (a == 0): return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) # Calculates a^{b} mod n when b is negative def neg_pow(a, b, n): assert b < 0 assert GCD(a, n) == 1 res = int(gmpy2.invert(a, n)) res = pow(res, b * (-1), n) return res g, a, b = egcd(e1, e2) if a < 0: c1 = neg_pow(c1, a, n) else: c1 = pow(c1, a, n) if b < 0: c2 = neg_pow(c2, b, n) else: c2 = pow(c2, b, n) ct = c1 * c2 % n m = int(gmpy2.iroot(ct, g)[0]) return long_to_bytes(m).decode('UTF-8')
def crack_times(self): k = -1 while True: k += 1 res, check = iroot(k * self.n + self.c, self.e) if check: break self.m = res
def solve(ct, e, n, padding_len): new_ct = ct * pow(modinv(256, n) ** padding_len, e, n) new_ct %= n for i in range(256): potential_pt, is_cube = gmpy2.iroot(new_ct + (n * i), e) if is_cube: print(i, long_to_bytes(potential_pt))
def Basic_Broadcast_Attack(data): if data['e'] == len(data['n']) == len(data['c']): t_to_e = chinese_remainder(data['n'], data['c']) t = int(gmpy2.iroot(t_to_e, data['e'])[0]) log.info('Here are your plain text: \n' + libnum.n2s(t)) else: log.error('wrong json file, check examples')
def decrypt_flag(rc, e, N, i): print 'Step {}/{}'.format(str(i).zfill(3), l) ct = pow(rc.ct, 2) * pow(2, i * e, N) res = rc.decrypt(ct % N) if res is not None: res = (res + N) // pow(2, i, N) return long_to_bytes(iroot(res, 2)[0])
def fake(h, padding, asn, size): pad = b'\x00\x01' + b'\xFF' * padding core = pad + b'\x00' + asn + h s = core + b'\x01' + b'\x00' * ((size // 8 - len(core))) sig, e = iroot(bytes_to_int(s), 3) for l, r in zip(core[1:], int_to_bytes(sig ** 3)): if l != r: return None return int_to_bytes(sig)
def hastads(self): # Hastad attack for low public exponent, this has found success for e = 3, and e = 5 previously if self.pub_key.e <= 11 and self.cipher is not None: orig = s2n(self.cipher) c = orig while True: m = gmpy2.iroot(c, self.pub_key.e)[0] if pow(m, self.pub_key.e, self.pub_key.n) == orig: self.unciphered = n2s(m) break c += self.pub_key.n return
def test_wiener(self): q = gmpy2.mpz(getPrime(512)) p = gmpy2.mpz(getPrime(512)) if q > p : p , q = q , p n = p * q phi = (p - 1) * (q - 1) d = gmpy2.iroot(n, 5)[0] while gmpy2.gcd(d, phi) != 1 : d -= 1 e = gmpy2.invert(d , phi) self.assertEqual((d, p, q), number.wiener_attack(n, e))
def factor_N2(N): '''Factor in correctly genrated N, which is a product of two relatively close primes p/q such that, |p-q| < 2^11*N^(1/4)''' N = mpz(N) sqrtN = gmpy2.isqrt(N) A = sqrtN for delta in range(0,2**20): A = sqrtN + delta if A*A < N: continue if gmpy2.iroot(A**2-N,2)[1]: # A^2-N is a perfect square return factor(A,N) return 0
def decrypt_by_public_key_root(public_key, n, ciphertext): ciphertext_bits = string_to_bits(ciphertext) ciphertext_int = bits_to_int(ciphertext_bits) PUBLIC_KEY_ROOT_ATTEMPTS = 10 for i in range(PUBLIC_KEY_ROOT_ATTEMPTS): plaintext_root_result = gmpy2.iroot(gmpy2.mpz(ciphertext_int + i * n), public_key) if plaintext_root_result[1]: plaintext_int = int(plaintext_root_result[0]) assert pow(plaintext_int, public_key) == ciphertext_int + i * n print("Found integer root of message") plaintext_bits = pad_bits(convert_to_bits(plaintext_int), MESSAGE_CHARS * ASCII_BITS) plaintext_string = bits_to_string(plaintext_bits).strip('\x00') assert is_valid_message(plaintext_string) return plaintext_string else: print("Root result is non-integer") print("Unable to decrypt by taking private key root") return None
def forgeSignature(msg, pk): (e, n) = pk msg_hash = hashlib.sha1(msg).digest() garbage = '\x00'*75 forge_sig = "\x00\x01\xff\x00" + sha1_asn1 + msg_hash + garbage forge_sig_num = int(binascii.hexlify(forge_sig), 16) # compute the cube root of our forged signature block (cube_root, exact) = gmpy2.iroot(forge_sig_num, 3) cube_root += 1 # make sure we don't wrap the modulus assert n > pow(int(cube_root), e) # recovered = int2bytes(pow(int(cube_root), pk[0], pk[1])) recovered = int2bytes(pow(int(cube_root), e, n)) assert "\x01\xff" in recovered assert sha1_asn1 in recovered assert msg_hash in recovered return int(cube_root)
def icbrt (a1, a2): z = gmpy2.iroot(mpz(a1), 3) return z[0]
c1 = 421111161283346431452404838872906910488956231402567019627078538397015129219548039141380131693083805603634832115136344104821561027925864923901767159809798556819390401416411855168293007844311613426948800208007055064348403326803934387258467126612219000171854953396242427891713082121012531213725355828779993888182933907101893044052692649728535361366924432892126370724588453260805681821935597271080255619110465374127164951502400983809536186925456642086304791751551216044579863129291165009342909475237361181743987301745314378124693429484474503217504889965795409106282650296184945237152875186651795552666842345066169360660546054986708172417429052514059615434084086154415920830883055729609108788179781445658162049137989591033198225687070565856609516100367268190340309308157085784134411282761584130225746032198957351227779773001865341915642873414205377145922729731246073639219795924517066513774579919237687232502798978463575009663263447306363691670476046609459059167879832079562689979943552446917015778003739858532004479603764374411135699895655736013845369551111690464128448955486337191304960262873891918387298035244888743768954328136862535082300010994461970837930794524673040694310506226189740828318579439950518115967189869637345638498098713092489244636082588805772227797143449747153355341250697133905040459624514982099584435140538668878747129925880019957973864264834954951976218071371679757509297492047186840975743403271896047156768874314108910566561868784522463064748746223313798316236978642468003218086919263188950066989044210829301678555320837086377545741001736801163743516580353549217680694256032377932133575488109549594325464409000682442042651791171660390153162096538381581148625792618196174157168997050557100450557288143739840824092541232969307054965994887340364612034225310418659933594966854225109483090892335755747449339249960596843266176465016510244036725441439565001070917883074011690676911331738356675397441288471244334501091751395240775991013123686801229872759306547212076067886148629332008410208267030715989530663720054487572883736818402878156320070866728567321649066842627412668340251628750512807830348760198570727092664649603270152943231283098179852700308804060616603604109118233213539629764618927518884532667481665405755714542980086417296700138731812815602896287231173509006149715343922041354056256194681983557852276963918040964106582078239501915086320391282791023780691061950154312894926940866878046518974877055347229774579384836298084254309194742164500782 c2 = 905336011260893181451937420601175770518313987534058470576409049452599974940736949020892631904955374029696187995214208522797070994604711663756814784706053753391830801248808142181434422224620348115969075398677162880328104668870990618955018212918253536803780269490731174871303579036880145367252409300321511403369634435527150000969450834032455903281526350857234024199221097951905683106432984567192925721856154512618509568221546898136983740670694848845816274649037002810596080076911851084982546841069002779200879395931456796911067433329924739943299552475793965462348342813683729525726622940637841204356613245154725191731818570068876251576706021876289420301350487275708440713574921631267131651109260124766475594710481161866254565495750886839979733888772439130815149472846472765436552529628205718020374215877005469575372812773398343007234021177110808440750777736752300216949812950208548770769356889084232841311299404061610926387440620373137543532240294565244268885021138356121583352086433040479579285669028705571672002026293450745788592556823683194951826864141604029265650908715426822940827714455571796485962047146479512064410497475912291097113335318214286537554114706858926411912595063427662813512257156617697572638072509013871077829931469009241562237896598800666350337578826848041056097241547835195327840625894306586665539851835002956883837883293039313345815320389859457247452362675082429215289259947007386622301346393036750250168159297672722825807855637539796284414040339895615478904699195785762873300869004533530925681372154050324943727448464697359515536114806520493724557784204316395281200493439754546212305945038548703862153513568552164320556554039878316192239576925690599059819274827811660423411125130527352853059068829976616766635622188402967122171283526317336114731850274527784991508989562864331372520028706424190362623058696630974348010681878756845430600722349325469186628612347668798617024215127322351935893754437838675067920448401031834465304168738463170328598024532652790234530162187677742373772610227011372650971705426850962132725369442443471111605896253734934335599889785048210986345764273409091402794347076211775580564523705131025788768349950799136508286891544854890654019681560870443838699627458034827040931554727774022911060988866035389927962128604944287104134091087855031454577661765552937836562030914936714391213421737277968877508252894207799747341644008076766221537325719773971004607956958298021339118374168598829394997802039272072755111105775037781715 g, s, t = gmpy2.gcdext(e1, e2) assert e1 * s + e2 * t == 1 if s < 0 and t > 0: c1i = gmpy2.invert(c1, N) m = (pow(c1i, -s, N) * pow(c2, t, N)) % N elif s > 0 and t < 0: c2i = gmpy2.invert(c2, N) m = (pow(c1, s, N) * pow(c2i, -t, N)) % N else: print "WTF", e1, e2, s, t exit() for i in xrange(1024): a = 1 << (i*8) a17 = pow(a, 17, N) a17i = gmpy2.invert(a17, N) m2 = (m * a17i) % N mroot, foundexact = gmpy2.iroot(m2, 17) if foundexact: pt = ("%x" % mroot) if len(pt) % 2 == 1: pt = "0" + pt print repr(binascii.a2b_hex(pt))
import gmpy2, binascii N = 691611766208546073444876122261067788277978858453710639029761974358666489171591889808344592871468081368348731289584873825685836699513369087940744233044470468106283756269016888690397802087612562650740690626844050981638158798650899164329024889012339813251634342169796374490173324858177655412520581064091323105709703802894635752243504165527728325493775585018099572491218738859140069209745383085972126419677929983854492018948495162457428459536088314487922683148031388611849013227501962458386817851194913551405843074740308192841259015955432216658418219471365781271743026881045054161177699500233983945284463060091084401032681620162554495490307966608011765399197534175588394769839991952726269105973546086964385977836193216093842605576347580465390858378577913173391209728199847916944392685608959720919745441534152140791433228642857247821519585327091864890122871765266988285510728943279970135846908966516130597249552710186071954611133294079017500030355232895541367427153922527925908108643934213023557398363684188823565535815365161748782796247844503993809352854741573950620787090272760236473228652960605730173150252619759400890068298838592790770868307280012495168740250977525199965477849089021924445456338550258621310346872587368865023459114279 e1 = 2623119 / 3 e2 = 2611101 / 3 c1 = 632613645684838434911920364870092246688638723680203743297038042884981435531349983627632652213126007404455112992754038899192740232209237012089852184466576496173356903126767617531366105427616049893559911396536574555008451239827427140619373005107923039458285095437111146013805698400274937791209388463040761234346114146112603113513874269976957472698342250573902102976387047390228485927254752372525379266486917620487089416581168720140744193600912161065888758451629009978676721731074043142666019127528370181044741033938879227651226413524178992155234346229899043794846119210274959231350300191718278291314079326011260972911790929707654859407903619102516710246683375658271085356783673232677699444921875427077745087507202504075374873842972977165904031632108921391219453633100007509368853543202918527396858214941532156620908283394786740941868393377733920317480973184132461984594109692489226477402338664642727766514992506288377119275635222078018270479534265371971469799345627297451492177595572561618185463142728664331779856911512823762928116551034186671353283417747535010208121962539603383913657773795358612010178381857101029638404248669376029927680328805839410427459248430136708902815920536603541943356116875656311481908672896225539754812052984 c2 = 473583830101449207063655453483957320801977763405664178108962387145963115641321631378723122470718049239150183483107837540062110255460217493574236417576528210993551734521104360323008425196350719034294427914294044848231276934402896045785500160974092767601908407706594433190832523140982335688121038712802163776950422665847149664034820576774873956120202470663588902529914328392634164212558025176982387474287314624421143326789371057668708456922968762564019631616913937820209470604081356673188045257490667304640155390478645279862586730343779998826931285683980941686981775369499484033439920659579124275957233449431588512697916708510428626881790592757578867152025501459202793986322020476004209777449674143157280081483085868896558215825742742029607229809248023263081810931655981810534293127835168642962477010095223356972141559004635008185531900175232541978761179342338914489553003329293031284557554252476291770973145365678145226167965362251186233138510776436645583796590010200995100899736056399413460647507781994189935869541735701599175369334170081795310585938471394672279359692859881857399434361716843681313191143289947464231132723256066979526475873327590657111481299295002695482778491520250596998683754980263059514032256777144682239680031331 g, s, t = gmpy2.gcdext(e1, e2) assert e1 * s + e2 * t == 1 if s < 0 and t > 0: c1i = gmpy2.invert(c1, N) m = (pow(c1i, -s, N) * pow(c2, t, N)) % N elif s > 0 and t < 0: c2i = gmpy2.invert(c2, N) m = (pow(c1, s, N) * pow(c2i, -t, N)) % N else: print "WTF", e1, e2, s, t exit() mroot, foundexact = gmpy2.iroot(m, 3) if foundexact: pt = ("%x" % mroot) if len(pt) % 2 == 1: pt = "0" + pt print repr(binascii.a2b_hex(pt))
import gmpy2 from gmpy2 import mpz from hashlib import sha1 message = "cat flag" # ls first time messagesha = sha1(message.encode("ascii")).hexdigest() # sha1 of message targetsig = "0001" + "f" * 8 + "00" + messagesha + "f" * 714 # target signature targethex = int(targetsig, 16) # target signature, converted to an int icbrt = gmpy2.iroot(mpz(targethex), 3) # integer cube root # note: icbrt is a tuple of (result, exact). # exact is True if it is a perfect cube root, False otherwise perfectcube = icbrt[0] ** 3 # cube cube root print(hex(perfectcube)) # print hex value, the result
def introot(n, r=2): if n < 0: return None if r%2 == 0 else -introot(-n, r) return iroot(n, r)[0]
def cube_root(n): return int(iroot(mpz(n), 3)[0])
if p*q == N: print("second factoring challenge") print("p=",p) break # third assignment N=720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 B = gmpy2.isqrt(24*N) + 1 tmp = B*B-24*N woop = gmpy2.iroot(tmp,2) if woop[1] == True: x = woop[0] else: print("not a square") quit() tmp = B - x if not tmp%3: p = gmpy2.divexact(tmp,6) q = gmpy2.divexact(B+x,4) else: p = gmpy2.divexact(tmp,4) q = gmpy2.divexact(B+x,6)