def sign(self, x, lambada): """ Sign the message x. """ gamma = pow(self.alpha, lambada, self.p) delta = ((x - self.priv * gamma) * utils.inv_modulo(lambada, self.p - 1)) % (self.p - 1) return (gamma, delta)
def __init__(self, p=None, q=None, a=None, b = None, n=None, nb_bits=4096): """Initializes the magic keys. """ if p is None and q is None and a is None: # 1. Generates 'p' and 'q' prime numbers of lengths 'nb_bits' in a # random fashion. if p is None and q is None: p = random.getrandbits(nb_bits) q = random.getrandbits(nb_bits) while not utils.miller_rabin(p): p = random.getrandbits(nb_bits) while not utils.miller_rabin(q): q = random.getrandbits(nb_bits) if a is None and b is None and n is None: # 2. Generates 'a', 'b' and 'n' thanks to 'phi' and 'b'. n = p * q phi = (p - 1) * (q - 1) if b is None: while True: b = random.randint(2, phi - 1) if utils.is_prime_together(b, phi): break a = utils.inv_modulo(b, phi) self.private = a self.public = b self.modulus = n
def sign(self, m, k): md5obj = hashlib.md5() md5obj.update(str(m)) digest = md5obj.hexdigest() mhash = int(digest,16) r = pow(self.g, k, self.p) s = ((mhash - self.priv * r) * utils.inv_modulo(k, self.p - 1)) % (self.p - 1) return (r, s)
def decrypt(cypher, cle): """ Afine decryption """ inv = utils.inv_modulo(cle[0], 26) return [(chr(((ord(i) - 65 - cle[1]) * inv) % 26 + 65)) for i in cypher]
def decrypt(self, y): """ Decrypt y. """ return (y[1] * utils.inv_modulo(pow(y[0], self.priv, self.p), self.p)) % self.p
import time if __name__ == '__main__': print("Factoring RSA modulus with weak prime factors\n") print("Loading RSA keys") rsa_obj = rsa.RSA(a=0, b=16219340638145739814556409984455971733340322034588741, n=19674270149491236515870218329564212980341362732018899) print(rsa_obj) print("Factoring the modulus...") start = time.time() factors = utils.factors_decomposition(rsa_obj.modulus) phi = (p - 1) * (q - 1) # guess what are p and q ? end = time.time() print("Factorisation done in {} seconds\n".format(end - start)) print(str(rsa_obj.modulus) + " = " + \ " * ".join([str(i) for i in factors]) + \ " = n * q ") print("Phi =", phi, "= (n - 1) * (q -1)") private = utils.inv_modulo(rsa_obj.public, phi) print("Private key: {}\n".format(private)) rsa_obj.private = private print('Submit this flag:') print( rsa_obj.decrypt_int( 332795103438906336586762421178058977844889453787945))