def search(K, Kp, Kq, check_level, break_step): max_step = 0 cands = [0] for step in range(1, break_step + 1): max_step = max(step, max_step) mod = 1 << (4 * step) mask = mod - 1 cands_next = [] for p, new_digit in product(cands, p_ranges[-step]): pval = (new_digit << ((step - 1) * 4)) | p if check_level >= 1: qval = solve_linear(pval, N & mask, mod) if qval is None or not check_val(qval, mask, qmask_msk, qmask_val): continue if check_level >= 2: val = solve_linear(E, 1 + K * (N - pval - qval + 1), mod) if val is None or not check_val(val, mask, dmask_msk, dmask_val): continue if check_level >= 3: val = solve_linear(E, 1 + Kp * (pval - 1), mod) if val is None or not check_val(val, mask, dpmask_msk, dpmask_val): continue if check_level >= 4: val = solve_linear(E, 1 + Kq * (qval - 1), mod) if val is None or not check_val(val, mask, dqmask_msk, dqmask_val): continue if pval * qval == N: print "Kq =", Kq print "pwned" print "p =", pval print "q =", qval p = pval q = qval d = invmod(E, (p - 1) * (q - 1)) coef = invmod(p, q) from Crypto.PublicKey import RSA print RSA.construct(map( long, (N, E, d, p, q, coef))).exportKey() quit() cands_next.append(pval) if not cands_next: return False cands = cands_next return True
def common_modulus_attack(c1, c2, e1, e2, n): s1, s2, _ = libnum.xgcd(e1, e2) if s1 < 0: s1 = s1 * -1 c1 = libnum.invmod(c1, n) if s2 < 0: s2 = s2 * -1 c2 = libnum.invmod(c2, n) m = (pow(c1, s1, n) * pow(c2, s2, n)) % n return m
def commonN(n, e1, c1, e2, c2): s1, s2, _ = xgcd(e1, e2) if s1 < 0: s1 = -s1 c1 = invmod(c1, n) if s2 < 0: s2 = -s2 c2 = invmod(c2, n) m = (pow(c1, s1, n) * pow(c2, s2, n)) % n return m
def search(K, Kp, Kq, check_level, break_step): max_step = 0 cands = [0] for step in range(1, break_step + 1): #print " ", step, "( max =", max_step, ")" max_step = max(step, max_step) mod = 1 << (4 * step) mask = mod - 1 cands_next = [] for p, new_digit in product(cands, p_ranges[-step]): pval = (new_digit << ((step - 1) * 4)) | p if check_level >= 1: qval = solve_linear(pval, N & mask, mod) if qval is None or not check_val(qval, mask, qmask_msk, qmask_val): continue if check_level >= 2: val = solve_linear(E, 1 + K * (N - pval - qval + 1), mod) if val is None or not check_val(val, mask, dmask_msk, dmask_val): continue if check_level >= 3: val = solve_linear(E, 1 + Kp * (pval - 1), mod) if val is None or not check_val(val, mask, dpmask_msk, dpmask_val): continue if check_level >= 4: val = solve_linear(E, 1 + Kq * (qval - 1), mod) if val is None or not check_val(val, mask, dqmask_msk, dqmask_val): continue if pval * qval == N: print "Kq =", Kq print "pwned" print "p =", pval print "q =", qval p = pval q = qval d = invmod(E, (p - 1) * (q - 1)) coef = invmod(p, q) from Crypto.PublicKey import RSA print RSA.construct(map(long, (N, E, d, p, q, coef))).exportKey() quit() cands_next.append(pval) if not cands_next: return False cands = cands_next return True
def get_ed(p, q): k = cal_bit(q*p) phi_n = (p-1)*(q-1) r = random.randint(10, 99) while True: u = getPrime(k/4 - r) if gcd(u, phi_n) != 1: continue t = invmod(u, phi_n) e = pi_b(t) if gcd(e, phi_n) == 1: break d = invmod(e, phi_n) return (e, d)
def get_ed(p, q): k = cal_bit(q * p) phi_n = (p - 1) * (q - 1) r = random.randint(10, 99) while True: u = getPrime(k / 4 - r) if gcd(u, phi_n) != 1: continue t = invmod(u, phi_n) e = pi_b(t) if gcd(e, phi_n) == 1: break d = invmod(e, phi_n) return (e, d)
def GetED(p, q): k = CalBit(q * p) phi_n = (p - 1) * (q - 1) r = random.randint(10, 99) while True: u = getPrime(k / 4 - r) if gcd(u, phi_n) != 1: continue t = invmod(u, phi_n) e = PiB(t) if gcd(e, phi_n) == 1: break d = invmod(e, phi_n) return (e, d)
def common_modulus(e1, e2, c1, c2, N): # Extended Euclidean algorithm a, b, d = xgcd(e1, e2) # Invert negative factor if b < 0: c2 = invmod(c2, N) b = -b if a < 0: c1 = invmod(c1, N) a = -a # Get the message (c1^a * c2^b) % N return (pow(c1, a, N) * pow(c2, b, N)) % N
def getFlag((a, b, c)): M = d["M"] p = d["p"] q = d["q"] s1, s2, _ = xgcd(a, b) if s1 < 0: s1 = -s1 p = invmod(p, M) elif s2 < 0: s2 = -s2 q = invmod(q, M) flag = (pow(p, s1, M) * pow(q, s2, M)) % M print n2s(flag)
def keys(pub, priv, floor, ceil): """ pub - list for public key; priv - list for private key; floor - lower boundary for random prime number generator; ceil - upper boundary for random prime number generator; """ p = 0 #prime number №uno q = 0 #prime number №dos q = randprime(floor, ceil) p = randprime(floor, ceil) print("*" * 10, "p=" + str(p), "q=" + str(q), "*" * 10, sep="\n") n = p * q phi = (p - 1) * (q - 1) e = prevprime(phi) pub.append(e) pub.append(n) #private key d = libnum.invmod(e, phi) priv.append(d) priv.append(n)
def encrypt(msg): bits = 60 if (len(sys.argv) > 1): msg = str(sys.argv[1]) if (len(sys.argv) > 2): bits = int(sys.argv[2]) p = Crypto.Util.number.getPrime(bits, randfunc=get_random_bytes) q = Crypto.Util.number.getPrime(bits, randfunc=get_random_bytes) n = p * q PHI = (p - 1) * (q - 1) e = 65537 d = libnum.invmod(e, PHI) m = bytes_to_long(msg.encode('utf-8')) c = pow(m, e, n) res = pow(c, d, n) print( "Message=%s\np=%s\nq=%s\n\nd=%d\ne=%d\nN=%s\n\nPrivate key (d,n)\nPublic key (e,n)\n\ncipher=%s\ndecipher=%s" % (msg, p, q, d, e, n, c, (long_to_bytes(res))))
def sign(self, d, e): """ Returns a DER serialized signature of message e using private key d. d is a private key (integer). e is an encoded message (integer). """ z = self.shrink_message(e) k, r = None, None while True: k = self.randint(self.n - 1) + 1 P = self.point_multiply(k, self.G) r = P.x % self.n if r == 0: continue s = invmod(k, self.n) * (z + (r * d) % self.n) % self.n if s != 0: break # Byte sizes of r, s rBn = (r.bit_length() + 7) // 8 sBn = (s.bit_length() + 7) // 8 # Byte sizes of components and sequence bytes mBn = 4 + rBn + sBn # Numeric representation of the DER serialized sig sig = [0x30, mBn, 0x02, rBn, r, 0x02, sBn, s] # Return a hex string of all the sig bytes return ''.join([ '0' + f if len(f) % 2 else f \ for f in [format(x, '02x') for x in sig]])
def __init__(self, p=None, q=None): self.p = p if p is not None else libnum.generate_prime(512) self.q = q if q is not None else libnum.generate_prime(512) if self.q == self.p: self.q = libnum.generate_prime(512) n = self.p * self.q lbd = lcm(self.p - 1, self.q - 1) n2 = n * n g = secrets.randbelow(n2 - 1) + 1 l_val = self._l(pow(g, lbd, n2), n) while not libnum.has_invmod(l_val, n): g += 1 if g == n2: g = 1 l_val = self._l(pow(g, lbd, n2), n) gMu = libnum.invmod(l_val, n) self.public_key = (n, g) self.private_key = (lbd, gMu)
def verify(self, pkey, e, sig): """ Verifies a message e was signed by the owner of public key pkey. Returns True if e was signed by the owner of pkey. Raises AssertionError if the signature is invalid. pkey is a serialized public key. e is the encoded message. sig is the DER serialized message. """ # First we define modular exponent, which is # used to calculate the y from a compressed # public key. # This only works for curves with an integer # order n that is congruent to 3 mod 4. def pow_mod(x, y, z): n = 1 while y: if y & 1: n = n * x % z y >>= 1 x = x * x % z return n # Now unmarshall the public key P = Point(None, None) if pkey[:2] == '04': P = Point(int(pkey[2:66], 16), int(pkey[66:])) else: y_parity = int(pkey[:2]) - 2 x = int(pkey[2:], 16) a = (pow_mod(x, 3, self.p) + self.b) % self.p y = pow_mod(a, (self.p + 1) // 4, self.p) if y % 2 != y_parity: y = -y % self.p P = Point(x, y) # P must not be point at infinity assert P != EllipticCurve.inf # P must lie on the curve y = P.y * P.y x = P.x * P.x * P.x + self.a * P.x + self.b assert y % self.p == x % self.p # Now unmarshall the signature assert sig[:2] == '30' # DER SEQUENCE byte mBn = int(sig[2:4], 16) # bytes in message assert sig[4:6] == '02' # DER INTEGER byte rBn = int(sig[6:8], 16) # bytes in r r = int(sig[8:8 + rBn * 2], 16) # r value assert sig[8 + rBn * 2:8 + rBn * 2 + 2] == '02' # DER INTEGER byte sBn = int(sig[8 + rBn * 2 + 2:8 + rBn * 2 + 4], 16) # bytes in s assert sBn == len(sig[8 + rBn * 2 + 4:4 + mBn * 2]) // 2 s = int(sig[8 + rBn * 2 + 4:4 + mBn * 2], 16) # s value # Now we have (r,s) and can verify z = self.shrink_message(e) w = invmod(s, self.n) U1 = self.point_multiply(z * w % self.n, self.G) U2 = self.point_multiply(r * w % self.n, P) R = self.point_add(U1, U2) assert r == R.x return True
def gen_args(): p=getPrime(1024) q=getPrime(1024) n=p*q e=0x10001 d=invmod(e,(p-1)*(q-1))%((p-1)*(q-1)) return (p,q,e,n,d)
def main(): rsa_key = rsaGen.construct_key() rsaGen.convert_der(rsa_key) rsaGen.print_values() message = '5' signature = rsaGen.sign_message(message) val1 = (message2 * pow(r, rsaGen.getPublicExponent(), rsaGen.getPublicModulus())) val2 = val1 % rsaGen.getPublicModulus() print("Value sent by Heather: ", val2) signed_dash = pow(val2, d, rsaGen.getPublicModulus()) print('Heather sends Alice signature: ', signed_dash) result = (signed_dash * libnum.invmod( r, rsaGen.getPublicModulus())) % rsaGen.getPublicModulus() print('Alice send signature of:', result) print('\n=== Check ==') unsigned = pow(result, rsaGen.getPublicExponent(), rsaGen.getPublicModulus()) print('Unsigned value is:', unsigned) if (unsigned == rsaGen.getMessageHash()): print('Success. Bob has signed it') else: print('Signatures do not compute')
def rabin(N, c, p, q): inv_p = libnum.invmod(p, q) inv_q = libnum.invmod(q, p) mp = pow(c, (p + 1) / 4, p) mq = pow(c, (q + 1) / 4, q) a = (inv_p * p * mq + inv_q * q * mp) % N b = N - int(a) c = (inv_p * p * mq - inv_q * q * mp) % N d = N - int(c) for i in (a, b, c, d): s = '%x' % i if len(s) % 2 != 0: s = '0' + s log.info('Here are your plain text: \n' + s.decode('hex'))
def point_double(self, P): """ Return P + P """ if P == EllipticCurve.inf: return P s = ((3 * P.x * P.x + self.a) * invmod(2 * P.y, self.p)) % self.p x = (s * s - 2 * P.x) % self.p y = (s * (P.x - x) - P.y) % self.p return Point(x, y)
def genE(lcm, bound): while True: r = random.randint(bound, bound * 0x1000000000001) d = sympy.nextprime(r) e = libnum.invmod(d, lcm) if isPrime(e): break return e
def generate_RSA(): p = getPrime(1024) q = getPrime(1024) n = p * q phi = (p - 1) * (q - 1) e = 65537 d = libnum.invmod(e, phi) assert (e * d) % phi == 1 return n, e, d
def decrypt(ciph, key): n = key[0] * key[1] tn = (key[0] - 1) * (key[1] - 1) print "key1:", key[0] print "key2:", key[1] print "tn:", tn d = libnum.invmod(3, tn) m = pow(ciph, d, n) print "m:", m return m
def add(self, p1, p2): if p1 == self.zero: return p2 if p2 == self.zero: return p1 x1, y1 = p1 x2, y2 = p2 if x1 != x2: l = (y2 - y1) * invmod(x2 - x1, P) else: l = 2 * self.a * x1 + self.b x = ((l - self.b) * invmod(self.a, P) - self.zero[0]) % P y = ((x - self.zero[0]) * l + self.zero[1]) % P return (x, y)
def keygenerate(): p = Crypto.Util.number.getPrime(bits,randfunc = Crypto.Random.get_random_bytes) q = Crypto.Util.number.getPrime(bits,randfunc= Crypto.Random.get_random_bytes) phi = (p-1)*(q-1) n = p*q e = 65537 d = (libnum.invmod(e,phi)) return (d,n)
def decrypt(ciph, key): n = key[0] * key[1] tn = (key[0]-1)*(key[1]-1) print "key1:", key[0] print "key2:", key[1] print "tn:", tn d = libnum.invmod(3, tn) m = pow(ciph, d, n) print "m:", m return m
def rsa_keygen(): bits = 100 p = getPrime(bits) q = getPrime(bits) n = p * q PHI = (p - 1) * (q - 1) e = getPrime(bits) d = libnum.invmod(e, PHI) return ((e, n), (d, n))
def get_keys(): p = Crypto.Util.number.getPrime(bits, randfunc=get_random_bytes) q = Crypto.Util.number.getPrime(bits, randfunc=get_random_bytes) n = p * q PHI = (p - 1) * (q - 1) e = 65537 d = libnum.invmod(e, PHI) return d, e, n
def calc(x,y,a): ans=0 for i in range(len(y)): tmp1=1 tmp2=1 for j in range(len(y)): if i !=j: tmp1*=(a-x[j]) tmp2*=(x[i]-x[j]) ans +=(tmp1*y[i]*invmod(tmp2,p))%p return ans%p
def sign(self, msg): e= Crypto.Util.number.getPrime(self.bit, randfunc=Crypto.Random.get_random_bytes) # e_1=(gmpy2.invert(e, p-1)) e_inv=(libnum.invmod(e, self.p-1)) #D= bytes_to_long(msg.encode('utf-8')) // if you want direct signing D = int.from_bytes(hashlib.sha256(msg).digest(),byteorder='big' ) Sign_r=pow(self.g, e, self.p) Sign_s=((D-self.x*Sign_r)*e_inv) % (self.p-1) print ("\nS_1= %s" % Sign_r) print ("S_2=%s" % Sign_s) return Sign_r, Sign_s
def main(): r = remote("115.159.191.193", 12000) # r = process("rsa1.py") verify(r) r.readuntil("token: ") token = "81755de89626aba8db7de4c93e658b68wBJekMIo" r.sendline(token) r.readuntil("n: ") n = r.readline().strip() n = int(n[2:-1], 16) r.readuntil("e: ") e = r.readline().strip() e = int(e[2:-1], 16) r.readuntil("is: ") enc_flag = r.readline().strip() enc_flag = int(enc_flag[2:-1], 16) print "We know:" print "n: ", hex(n) print "e: ", hex(e) print "flag: ", hex(enc_flag) print "=======Start Attack======" t = pi_b(e) print "get t = ", hex(t) phi_n = wiener_attack(t, n) try: u = invmod(t, phi_n) except: return False print "get u = ", hex(u) qq, pp = divide_pq(u * t, n) print "get p = ", hex(pp) print "get q = ", hex(qq) d = invmod(e, (qq - 1) * (pp - 1)) print "get d = ", hex(d) flag = pow(enc_flag, d, n) print "get flag: ", long_to_bytes(flag)
def main(): r = remote("115.159.191.193", 12000) # r = process("rsa1.py") verify(r) r.readuntil("token: ") token = "81755de89626aba8db7de4c93e658b68wBJekMIo" r.sendline(token) r.readuntil("n: ") n = r.readline().strip() n = int(n[2:-1], 16) r.readuntil("e: ") e = r.readline().strip() e = int(e[2:-1], 16) r.readuntil("is: ") enc_flag = r.readline().strip() enc_flag = int(enc_flag[2:-1], 16) print "We know:" print "n: ", hex(n) print "e: ", hex(e) print "flag: ", hex(enc_flag) print "=======Start Attack======" t = pi_b(e) print "get t = ", hex(t) phi_n = wiener_attack(t, n) try: u = invmod(t, phi_n) except: return False print "get u = ", hex(u) qq, pp = divide_pq(u*t, n) print "get p = ", hex(pp) print "get q = ", hex(qq) d = invmod(e, (qq-1)*(pp-1)) print "get d = ", hex(d) flag = pow(enc_flag, d, n) print "get flag: ", long_to_bytes(flag)
def Broadcast_Attack(ciphertexts, public_exponent, modules): N = reduce(lambda res, x: res * x, modules, 1) result = 0 for i in xrange(len(modules)): temp = list(modules[:]) value = temp.pop(i) module = reduce(lambda res, x: res * x, temp, 1) opposite = (libnum.invmod(module, value)) result += str_to_num(ciphertexts[i]) * (N / modules[i]) * opposite result = (result % N) result = result**sympy.Rational(1, public_exponent) return num_to_str(int(result))
def test_invmod(self): for modulus in range(2, 1000, 37): for a in range(2, modulus, 5): if libnum.has_invmod(a, modulus): x = libnum.invmod(a, modulus) self.assertEqual((a * x) % modulus, 1) else: self.assertRaises(ValueError, libnum.invmod, a, modulus) self.assertRaises(ValueError, libnum.invmod, 1, 1) self.assertRaises(ValueError, libnum.invmod, 1, 0) self.assertRaises(ValueError, libnum.invmod, 1, -100) self.assertRaises(TypeError, libnum.invmod, "qwe", 10) self.assertRaises(TypeError, libnum.invmod, 10, "qwe")
def point_add(self, P, Q): """ Return P + Q """ if P == EllipticCurve.inf: return Q if Q == EllipticCurve.inf: return P if P.x == Q.x: if (P.y + Q.y) % self.p == 0: return EllipticCurve.inf return self.point_double(P) s = ((Q.y - P.y) * invmod(Q.x - P.x, self.p)) % self.p x = (s * s - P.x - Q.x) % self.p y = (s * (P.x - x) - P.y) % self.p return Point(x, y)
def mainECC(): global exefile exe = open(exefile, "rb") plaintext = exe.read(32) global cryptofile f = open(cryptofile, "rb") ciphertext = f.read(32) gamma = map(get_gamma_symbol, ciphertext, plaintext) coordinate = int("0x" + "".join(gamma), 0x10) exe.close() #init elliptic Curve global a, b, p, order, G curve = libnum.ecc.Curve(a, b, p, order=order, g=G) points = curve.check_x(coordinate) if not points: raise Exception("No points on a curve with such x-coordinate!") global F d = libnum.invmod(backdoor, order) F = curve.generate(backdoor) valid_seeds = [] #here the key moment for point in points: value = curve.power(point, d)[0] valid_seeds.append(value) print valid_seeds #here we must choose one of the seeds - 0 or 1 #feel free to modify this value seed = valid_seeds[1] global outputfile exe = open(outputfile, "wb") exe.write(plaintext) f.seek(32, 0) filesize = os.path.getsize(cryptofile) print filesize / 32 #decryption_cycle: for _ in xrange(filesize / 32): print("%d cycle" % _) seed = decryption(curve, seed, f, exe) if filesize % 32: decryption(curve, seed, f, exe, True) f.close() exe.close()
def main(): verify() usage = """ 01010111 01100101 01101100 01100011 01101111 01101101 01110100 01101111 00110010 00110000 00110001 00110110 01001000 01000011 01010100 01000110 01010010 01010011 01000001 01000100 01100101 01100011 01101111 01100100 01100101 01010011 01111001 01110011 01110100 01100101 01101101 """ print usage print "This is a RSA Decryption System" print "Please enter Your team token: " try: token = raw_input() flag = get_flag(token) assert len(flag) == 38 except: print "Token error!" m_exit(-1) spub, spriv = get_pkey() # Generation p, q p, q = GetPrimes(spub, spriv) n = p * q phi_n = (p-1)*(q-1) d = invmod(e, phi_n) while True: e2 = random.randint(0x1000, 0x10000) if gcd(e2, phi_n) == 1: break print "In this Game, Your public key:" print "n: ", hex(n) print "e: ", hex(e) print "e2: ", hex(e2) flag = bytes_to_long(flag) enc_flag = pow(flag, e2, n) print "Your flag is: ", hex(enc_flag) print "============Start Games============" print "Please enter your cipher: " while True: s = raw_input() try: c = int(s) except: m_exit(-1) m = pow(c, d, n) print "Your Plaintext is: ", hex(m) time.sleep(1)
def main(): verify() usage = """ 01010111 01100101 01101100 01100011 01101111 01101101 01110100 01101111 00110010 00110000 00110001 00110110 01001000 01000011 01010100 01000110 01010010 01010011 01000001 01000100 01100101 01100011 01101111 01100100 01100101 01010011 01111001 01110011 01110100 01100101 01101101 """ print usage print "This is a RSA Decryption System" print "Please enter Your team token: " try: token = raw_input() flag = get_flag(token) assert len(flag) == 38 except: print "Token error!" m_exit(-1) spub, spriv = get_pkey() # Generation p, q p, q = GetPrimes(spub, spriv) n = p * q phi_n = (p - 1) * (q - 1) d = invmod(e, phi_n) while True: e2 = random.randint(0x1000, 0x10000) if gcd(e2, phi_n) == 1: break print "In this Game, Your public key:" print "n: ", hex(n) print "e: ", hex(e) print "e2: ", hex(e2) flag = bytes_to_long(flag) enc_flag = pow(flag, e2, n) print "Your flag is: ", hex(enc_flag) print "============Start Games============" print "Please enter your cipher: " while True: s = raw_input() try: c = int(s) except: m_exit(-1) m = pow(c, d, n) print "Your Plaintext is: ", hex(m) time.sleep(1)
def partial_q(e,dp,dq,qi,part_q): # Tunable to search longer N = 100000 for j in range(N,1,-1): q = (e * dq -1)/j +1 if str(hex(q)).strip('L').endswith(part_q): break for k in range(1,N,1): p = (e * dp -1)/k +1 try: m = libnum.invmod(q, p) if m == qi: break except: pass print "p = " + str(p) print "q = " + str(q)
#!/usr/bin/python import base64 import libnum n1 = 123948613128507245097711825164030080528129311429181946930789480629270692835124562568997437300916285601268900901495788327838386854611883075845387070635813324417496512348003686061832004434518190158084956517800098929984855603216625922341285873495112316366384741709770903928077127611563285935366595098601100940173 n2 = 122890614849300155056519159433849880305439158904289542874766496514523043027349829509818565800562562195671251134947871996792136355514373160369135263766229423623131725044925870918859304353484491601318921285331340604341809979578202817714205469839224620893418109679223753141128229197377934231853172927071087589849 e = 65537 q = libnum.gcd(n1,n2) # calculate gcd to discover a prime factor in common p = n1 / q phi = (p-1) * (q - 1) c = libnum.s2n(base64.b64decode(open('ciphertext.txt','r').read())) d = libnum.invmod(e,phi) m = pow(c,d,n1) print "[+] Flag: " + libnum.n2s(m)
def phiN(e, d, k): return ((e * d) - 1) / k def wiener_attack(e, n): pq = partial_quotiens(e, n) c = convergents(pq) x = Symbol('x') print 'done' for (k, d) in c: if d != 196176397553781094149364022413702698618416570027142099596910222792686220199799634430113040703408219640551905602804050764120518037301734891772260502596755642106767631991390703026953707346708504142195119698789998222566587930259938572562702895638995035040020739921966671123993267592460124879940448923: continue if k != 0: y = n - phiN(e, d, k) + 1 roots = solve(x**2 - y*x + n, x) if len(roots) == 2: p = roots[0] q = roots[1] if p * q == n: break return p, q bt = 536380958350616057242691418634880594502192106332317228051967064327642091297687630174183636288378234177476435270519631690543765125295554448698898712393467267006465045949611180821007306678935181142803069337672948471202242891010188677287454504933695082327796243976863378333980923047411230913909715527759877351702062345876337256220760223926254773346698839492268265110546383782370744599490250832085044856878026833181982756791595730336514399767134613980006467147592898197961789187070786602534602178082726728869941829230655559180178594489856595304902790182697751195581218334712892008282605180395912026326384913562290014629187579128041030500771670510157597682826798117937852656884106597180126028398398087318119586692935386069677459788971114075941533740462978961436933215446347246886948166247617422293043364968298176007659058279518552847235689217185712791081965260495815179909242072310545078116020998113413517429654328367707069941427368374644442366092232916196726067387582032505389946398237261580350780769275427857010543262176468343294217258086275244086292475394366278211528621216522312552812343261375050388129743012932727654986046774759567950981007877856194574274373776538888953502272879816420369255752871177234736347325263320696917012616273L e = 0x23f52cf5663b7c4725585b3aba7cccb1458937807da8fa5cefe5fec0b2a60ae4043bff95ed3e2b721901ca3db7a1ceff57fe26d37e9249737a65e3533ad8a2f86f5575165647981d44240d14040dca6f2450efcbb7e45ecbc1fab1f863fbdf4720b00291b423edafafae8df0aa8b76a7ee10d468102c25fe46c6064e4d874c3f9314937845663892f4343475179a55356af61b5a0e84f7a7e92e4c87168f6126289b781beb65762761bc94e1061936dc17232b603dee2e3f3d6a07dfa510f23d7b205b297ea2f874c595ee0a613fd74013befb163164fe916c5e83ee0add0039d858dd1dcbbde5c6c556eb88078d375ee6cce30047c5b453af90f9113615a0ab859d3ddf178acee80c6a16b5f5bd6d351ffcfba1ee2bae3b2596bd932fbc40b99206d2ae144b498cacca39c41e6f13d3df64e9993ede48fbad7f145a6afc7c3eca683ac025d11f7b5f1643784b487ff10357ab53549cd46a7c496effd5a8f2f28fbb9233287b5c4e0fb7b90a9ca503216faf6cba9233be8e5fc62dcaeae4b757437f6171dac83561d8dd0639515ced45ab3d56a8fd209b4ed1bdab9d863c1cfefe7daafa49095dd741085f39afa00fdf63eb7385ca1eb7c9c49f569d84c289bbecb23d0dd8e17766fa16ec317bae79e5c1277b6a3f291aa5e19dd6bcb4a66b796aeb664f14413bbbc3b6cdd827bd9b0cd284da1ad62822f5837ae555ad4f3009L n = 0x76fc639cc00be768d4c6ae1624b6ee8a94c07e3afa0da2bc34e483f235d496c08447b4285c93246cc9b4a952d219d9a47577644bc58facda642590ff37ad29a8f269d2ef07d436e8dbb9f610a4a64495eefbba07f7e5984d227476da17e8e522350a16d1aedb4135bca4d5f0343bca8c6f3fa2a3872e06113330153014bb62896e21abaed946d22dc7ac1259242b28f485fb31fc1de6c084a7f819e2881de21b1988a56f7590a47deb7bf872a2a05f6c6e314651ccfd0b1e048b5e9f693dc6b3a9c1cfd71a7ba6934767c98f4f2f241181c67e399e57c448b3a9bdcbb43d5344462c224d9c493e3f18453318a11c7cfd863fc1bae8fe95bf5c31460e213ea49f961cdee8aaa948c09023efbf602f74b7ff5ce50042f032dc6477f8bad33c490b1b9bf588a8fa580ba4ff274c76a339c065e459f5f88e273e80b0fd88f902cae331a91c6923636abe7446136e6a810aecc8c5ac10ce3c9c34f89ac2036193f17191839cade4df451b4a6f171b7ea4042ea7534bbbdffa6974cc64c8d59cdb04f76e6af011d3bb7f0c2cbfce1b13feaf54f8a0f7d32a2d11ab28e01385d6746d849140f71bffcc25fb20992d4a6bcbcf33e3b9e995a806839fa84b865200bd1c0b8f0466382c40323b834c77f822cc4583997fbe1770b1003c424a560889f8657cf2c7021aa59d71f4cc162b4bf7fe29e7a4d9dbf9f67efcc9a59025fc54ea1a9dL t = libnum.invmod(e, bt) print wiener_attack(t, n)
import libnum, string n = 0x219cc6aa0ec13d041c4971 m = 0xac470f7350ea67d7a0696 p = 1398023584459 q = 29065965967667 tot = (p-1)*(q-1) for e in libnum.primes(10000000): if tot % e != 0: d = libnum.invmod(e,tot) s = libnum.n2s(pow(m,d,n)) noprint = False for c in s: if c not in string.printable: noprint = True break if not noprint: print s
def main(): verify() usage = """ ** ** ** ********** /** /** /** /////**/// /** * /** ***** /** ***** ****** ********** /** ****** /** *** /** **///** /** **///** **////**//**//**//** /** **////** /** **/**/**/******* /**/** // /** /** /** /** /** /** /** /** /**** //****/**//// /**/** **/** /** /** /** /** /** /** /** /**/ ///**//****** ***//***** //****** *** /** /** /** //****** // // ////// /// ///// ////// /// // // // ////// ** ** ****** ********** ******** ******* ******** ** /** /** **////**/////**/// /**///// /**////** **////// **** /** /** ** // /** /** /** /** /** **//** /**********/** /** /******* /******* /********* ** //** /**//////**/** /** /**//// /**///** ////////** ********** /** /**//** ** /** /** /** //** /**/**//////** /** /** //****** /** /** /** //** ******** /** /** // // ////// // // // // //////// // // ******** **//////** ** // ****** ********** ***** /** //////** //**//**//** **///** /** ***** ******* /** /** /**/******* //** ////** **////** /** /** /**/**//// //******** //******** *** /** /**//****** //////// //////// /// // // ////// """ print usage print "This is a RSA Decryption System" print "Please enter Your team token: " try: token = raw_input() flag = get_flag(token) assert len(flag) == 38 except: print "Token error!" m_exit(-1) p, q, e = gen_key() n = p * q phi_n = (p-1)*(q-1) d = invmod(e, phi_n) while True: e2 = random.randint(0x1000, 0x10000) if gcd(e2, phi_n) == 1: break print "n: ", hex(n) print "e: ", hex(e) print "e2: ", hex(e2) flag = bytes_to_long(flag) enc_flag = pow(flag, e2, n) print "Your flag is: ", hex(enc_flag) print "============Start Games============" print "Please enter your cipher: " while True: try: s = raw_input() c = int(s) except: m_exit(-1) m = pow(c, d, n) print "Your Plaintext is: ", hex(m) time.sleep(1)
def pi_b(x): bt = 536380958350616057242691418634880594502192106332317228051967064327642091297687630174183636288378234177476435270519631690543765125295554448698898712393467267006465045949611180821007306678935181142803069337672948471202242891010188677287454504933695082327796243976863378333980923047411230913909715527759877351702062345876337256220760223926254773346698839492268265110546383782370744599490250832085044856878026833181982756791595730336514399767134613980006467147592898197961789187070786602534602178082726728869941829230655559180178594489856595304902790182697751195581218334712892008282605180395912026326384913562290014629187579128041030500771670510157597682826798117937852656884106597180126028398398087318119586692935386069677459788971114075941533740462978961436933215446347246886948166247617422293043364968298176007659058279518552847235689217185712791081965260495815179909242072310545078116020998113413517429654328367707069941427368374644442366092232916196726067387582032505389946398237261580350780769275427857010543262176468343294217258086275244086292475394366278211528621216522312552812343261375050388129743012932727654986046774759567950981007877856194574274373776538888953502272879816420369255752871177234736347325263320696917012616273L return invmod(x, bt)
print "[*] Solving layer 1: Weak key factored with ECM method" # layer 1 public key n = 94738740796943840961823530695778701408987757287583492665919730017973847138345511139064596113422435977583856843887008168202003855906708039013487349390571801141407245039011598810542232029634564848797998534872251549660454277336502838185642937637576121533945369150901808833844341421315429263207612372324026271327 e = 65537 # layer 1 factored with ECC method p = 9733382803370256893136109840971590971460094779242334919432347801491641617443615856221168611138933576118196795282443503609663168324106758595642231987245583 q = 9733382803370256893136109840971590971460094779242334919432347801491641617443615856221168611138933576118196795282443503609663168324106758595642231987246769 # valid p and q right!? assert(n % p == 0) assert(n % q == 0) c = libnum.s2n(open('almost_almost_almost_almost_there.encrypted','rb').read()) phi = (p - 1) * (q - 1) d = libnum.invmod(e, phi) m = pow(c,d,n) zippassword = libnum.n2s(m) ################### LAYER 2 ###################### print "[*] Solving layer 2: Common factors!" # unzip layer2 unzip = subprocess.check_output(['unzip','-o','-P',zippassword,'almost_almost_almost_almost_there.zip']) # get next modulus l2n = int(subprocess.check_output(['openssl', 'rsa', '-noout', '-modulus', '-pubin', '-in', 'almost_almost_almost_there.pub']).split('=')[1],16) # load ciphertext l2c = libnum.s2n(open('almost_almost_almost_there.encrypted','rb').read()) # layer 2 modulus has common factor with layer 1
def solve_linear(a, b, mod): if a & 1 == 0 or b & 1 == 0: return None return (b * invmod(a, mod)) & (mod - 1) # hack for mod = power of 2