Example #1
0
def main():
    groups = get_groups_nec("problem.txt")

    for x in groups:
        for y in groups:
            if x == y:
                continue

            n1, e1, c1 = x
            n2, e2, c2 = y

            # 涉及扩展欧几里德算法
            # 这里的算法得好好学习下, 怎么求出 a 和 b 的
            # a * e1 + b * e2 = 1
            if gmpy2.gcd(e1, e2) == 1:
                a = gmpy2.invert(e1, e2)
                b = int((gmpy2.gcd(e1, e2) - a * e1) / e2)

                assert (a * e1 + b * e2) == 1
                assert b < 0

                c2i = gmpy2.invert(c2, n1)
                c1a = gmpy2.powmod(c1, a, n1)
                c2b = gmpy2.powmod(c2i, -b, n1)
                m = c1a * c2b % n1
                print(binascii.unhexlify(hex(m)[2:]))
def pythag_triple_tree(triple=(3, 4, 5), forward=True, trust=False):
    """
    Primitive Pythagorean Triple (PPT) (a, b, c) is integer triple satisfying
        a**2 + b**2 = c**2
        gcd(a, b) = gcd(b, c) = gcd(a, c) = 1
    Given a PPT, it can generate three more PPTs. And if recursively applying this branching function from (3, 4, 5), all PPTs in form (odd, even, odd) can be generated in a trinary tree, which covers the entire set of PPTs completely and uniquely.
    When forward is True, return all three children of current PPT.
    When forward is False, return its parent in the PPT tree.
    """

    a, b, c = triple
    if not trust:
        if a**2 + b**2 != c**2:
            raise ValueError("Invalid Primitive Pythagorean Triple")
        if gcd(a, b) * gcd(a, c) * gcd(b, c) != 1:
            raise ValueError("Invalid Primitive Pythagorean Triple")

    if forward:
        return ((a-2*b+2*c,   2*a-b+2*c,  2*a-2*b+3*c),
                (a+2*b+2*c,   2*a+b+2*c,  2*a+2*b+3*c),
                (-a+2*b+2*c, -2*a+b+2*c, -2*a+2*b+3*c))
    else:
        if triple == (3, 4, 5):
            return triple
        else:
            return (abs(-a-2*b+2*c), abs(-2*a-b+2*c), -2*a-2*b+3*c)
def generate_public_key(bits_length=512, e=3):
    # 注意验证p和q的合法性, 要求与3互质
    while True:
        p = getPrime(bits_length)
        q = getPrime(bits_length)

        if gmpy2.gcd(p, e) == 1 and gmpy2.gcd(q, e) == 1:
            return gmpy2.mpz(p) * gmpy2.mpz(q), e
 def get_e_um_result(self, e):
     """
     网上给的一个公式, 好像可以直接计算出来
     [1 + gcd(e - 1, p - 1)] * [1 + gcd(e-1, q-1)]
     :param e: 11
     :return: 9
     """
     return (1 + gmpy2.gcd(e - 1, self.p - 1)) * (1 + gmpy2.gcd(e - 1, self.q - 1))
def crt(eqn1, eqn2):
    x1, m1 = eqn1
    x2, m2 = eqn2
    d = int(gmpy2.gcd(m1, m2))
    x = x1 + (m1 // d) * (x2 - x1) * int(gmpy2.invert(m1 // d, m2 // d))
    m = int(gmpy2.lcm(m1, m2))
    return x % m, m
Example #6
0
def could_be_prime(n):
   '''Performs some trials to compute whether n could be prime. Run time is O(N^3 / (log N)^2) for N bits.

Returns whether it is possible for n to be prime (True or False).
'''
   if n < 2:
      return False
   if n == 2:
      return True
   if not int(n) & 1:
      return False

   product = ONE
   log_n = int(math.log(n)) + 1
   bound = int(math.log(n) / (LOG_2 * math.log(math.log(n))**2)) + 1
   if bound * log_n >= n:
      bound = 1
      log_n = int(sqrt(n))
   prime_bound = 0
   prime = 3

   for _ in range(bound):
      p = []
      prime_bound += log_n
      while prime <= prime_bound:
         p.append(prime)
         prime = next_prime(prime)
      if p != []:
         p = prod(p)
         product = (product * p) % n

   return gcd(n, product) == 1
def create_rsa_keys(bits_length=512, e=65537):
    """
    产生有关 RSA 的一切参数, 包括 p, q, n ,phi_n, d, e
    本来想用 pycrypto 库的 RSA 来生成的, 但是这个库至少要求 1024bits, 还是自己手搓吧
    :param bits_length: p 和 q 的位长度限制
    :param e: 指定的 e
    :return: dict(), RSA 的一切参数作为字典返回
    """
    rsa = dict()
    while True:
        p = gmpy2.mpz(getPrime(bits_length))
        q = gmpy2.mpz(getPrime(bits_length))
        n = p * q
        phi_n = (p - 1) * (q - 1)

        if gmpy2.gcd(e, phi_n) == 1:
            break

    rsa["p"] = p
    rsa["q"] = q
    rsa["n"] = n
    rsa["phi"] = phi_n
    rsa["d"] = gmpy2.invert(e, rsa["phi"])
    rsa["e"] = e

    return rsa
Example #8
0
def factor_prime(prime):

    # p - 1 is 37-smooth
    base = 2
    k_sm = 37

    # pow(base,k_sm!) mod prime
    a = gmpy2.powmod(base, gmpy2.fac(k_sm), prime)

    # gcd(r_k - 1, prime)
    p = gmpy2.gcd(a-1, prime)

    # get second factor of prime
    q = (prime / p)

    # make sure factors (pq) are prime
    if (gmpy2.is_prime(p) and gmpy2.is_prime(q)):
        print "p = ", p
        print "q = ", q

        # make sure n = p*q = prime number
        n = gmpy2.mul(p,q)

        if (n == prime):
            print "n = ", gmpy2.mul(p,q)

    return
 def __generate_e(self):
     """
     生成器, 负责产生合理的 e 值以供选择
     :return: generator
     """
     for e in range(3, self.et):
         if gmpy2.gcd(e, self.et) == 1:
             yield e
def get_resilience(n):
    rescount = 0
    for i in xrange(1, n):
        if gmpy2.gcd(i, n) == 1:
            rescount = rescount + 1

    res = 1.0 * rescount / (n - 1)
    return res
 def generate_e(self):
     """
     产生 e 的生成器
     :return: e, e 满足 1 < e < φ(q,p), 且 gcd(e,φ)=1
     """
     for e in range(2, self.phi):
         if gmpy2.gcd(e, self.phi) == 1:
             yield e
def create_rsa_keys(bits_length=512, e=65537):
    # 本来想用pycrypto库的RSA来生成的, 但是这个库至少要求1024bits, 还是自己手搓吧
    rsa = dict()
    while True:
        p = getPrime(bits_length)
        q = getPrime(bits_length)

        if gmpy2.gcd(p, e) == 1 and gmpy2.gcd(q, e) == 1:
            break

    rsa["p"] = p
    rsa["q"] = q
    rsa["n"] = p * q
    rsa["phi"] = (p - 1) * (q - 1)
    rsa["d"] = gmpy2.invert(e, rsa["phi"])
    rsa["e"] = e

    return rsa
Example #13
0
def encrypt(pk, m):
    assert m < pk[0]
    while True:
        r = random.randint(1, pk[0])
        if gmpy2.gcd(r, pk[0]) == 1:
            break
    c1 = pow(pk[1], m, pk[0]**2)
    c2 = pow(r, pk[0], pk[0]**2)
    return (c1*c2) % pk[0]**2
Example #14
0
def ggcd(seq):
    """
    return the greatest common divisor (gcd) for n integers,
    where n can larger than 2
    """

    if len(seq) < 2:
        raise ValueError("There should be at least 2 integers!")
    elif len(seq) == 2:
        return gcd(seq[0], seq[1])
    else:
        g = gcd(seq[-2], seq[-1])
        if g == 1:
            return g
        for n in seq[:-2]:
            g = gcd(g, n)
            if g == 1:
                return 1
        return g
def chinese_remainder_theorem(eqn):
    '''
        eqn = [ (y_0, n_0), ... ] where
            x = y_i mod n_i
    '''
    x = 0
    m = 1
    for y, n in eqn:
        d = gmpy2.gcd(m, n)
        x += (m // d) * (y - x) * gmpy2.invert(m // d, n // d)
        m = gmpy2.lcm(m, n)
    return x % m
Example #16
0
def makeKey(n):
	privKey = [random.randint(1, 4**n)]
	s = privKey[0]
	for i in range(1, n):
		privKey.append(random.randint(s + 1, 4**(n + i)))
		s += privKey[i]
	q = random.randint(privKey[n-1] + 1, 2*privKey[n-1])
	r = random.randint(1, q)
	while gmpy2.gcd(r, q) != 1:
		r = random.randint(1, q)
	pubKey = [ r*w % q for w in privKey ]
	return privKey, q, r, pubKey
Example #17
0
def encrypt(pub, plain):
    while True:
        r=mpz_urandomb(rand, pub.bits)
        if r > 0 and r < pub.n and gcd(r,pub.n)==1:
            break
#        else: 
#            print r
# for sufficiently large pub.bits comment the previous while True loop and uncomment the following line 
#    r=mpz_urandomb(rand, pub.bits)
    x = powmod(r, pub.n, pub.n_sq)
    cipher = (powmod(pub.g, plain, pub.n_sq) * x) % pub.n_sq
    return cipher
Example #18
0
 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))
Example #19
0
File: laba5.py Project: boggad/labs
def gen_keys():
    rs = gmpy2.random_state(hash(gmpy2.random_state()))
    P = gmpy2.mpz_urandomb(rs, mpz('128'))
    P = gmpy2.next_prime(P)
    Q = gmpy2.mpz_urandomb(rs, mpz('128'))
    Q = gmpy2.next_prime(Q)
    N = P*Q
    Fi = (P-1)*(Q-1)
    Pkey = gmpy2.mpz_random(rs, Fi)
    while not (gmpy2.gcd(Fi, Pkey) == 1):
        Pkey = gmpy2.mpz_random(rs, Fi)
    Skey = gmpy2.invert(Pkey, Fi)
    assert gmpy2.t_mod(Skey*Pkey,Fi) == 1
    return Pkey, Skey, N
Example #20
0
def co_prime_tree(pair=(0, 0), trust=False):
    """
    All co-prime pairs can be generated from (2, 1) (for (odd, even) and (even, odd) pairs) and (3, 1) (for (odd, odd) pairs).
    It follows a trinary tree, from co-prime pair (a, b), we get: (2*a - b, a), (2*a + b, a), (a + 2*b, b)
    It can be shown that the co-prime pairs in the tree are disjoint complete.
    """

    if pair == (0, 0):
        return ((2, 1), (3, 1))

    a, b = pair
    if not trust:
        if gcd(a, b) != 1:
            raise ValueError("Invalid co-prime pair!")
    return ((2*a - b, a), (2*a + b, a), (a + 2*b, b))
Example #21
0
def hing(pairs):
    """Solves a set of simultaneous congurences using 
    a generalized CRT (Yih-Hing).
    For more detail see 
    "Elementary Number Theory", Gareth A.Jones and J. Mary Jones

    When running optimized this call never fails, 
    but may produce invalid results if no solution exists

    Args:
        pairs (list): An iterable of pairs(y, P),
            where P are the prime factors of z 
            (see crt function documentation)
            Notice that the moduli need not be 
            pairwise relativly prime!

    Returns:
        A positive integer with x = y mod product(P)
        for every pair (y, P)
    """

    # Check for existance of solution
    if __debug__:
        prods = {product(P): y for y, P in pairs}
        assert len(prods) == len(pairs)
        for z1, y1 in prods.items():
            for z2, y2 in prods.items():
                if (y1 - y2) % gcd(z1, z2) != 0:
                    raise NoSolution

    # Find the highest exponent
    part = {}
    for y, p in pairs:
        for f in set(p):
            e = p.count(f)
            try:
                if part[f][0] >= e:
                    continue
            except KeyError:
                pass
            part[f] = (e, y)

    # Produce regular CRT instance
    new = []
    for f, (e, y) in part.items():
        z = pow(f, e)
        new.append((y % z, z))
    return crt(new)
Example #22
0
 def test_crt_coprime(self):
     v = random.randint(10, 10000000000)
     n = random.randint(1, 100)
     remainders = []
     moduli = []
     lcm = 1
     for i in range(n):
         while True:
             mod = random.randint(2, 100000000)
             g = gmpy2.gcd(mod, lcm)
             if g == 1 : break
         remainders.append(v % mod)
         moduli.append(mod)
         lcm *= mod
     res = number.crt(remainders, moduli)
     self.assertEqual(res, (v % lcm, lcm))
Example #23
0
def matrixSimplify(mat, den):
    resultRows = len(mat)
    resultCols = len(mat[0])
    result = [[mpz(0) for x in xrange(resultCols)] for x in xrange(resultRows)]
    gcd = den
    
    for row in xrange(resultRows):
        for col in xrange(resultCols):
            gcd = gmpy2.gcd(gcd, mat[row][col])
            
    for row in xrange(len(mat)):
        for col in xrange(len(mat[0])):
            result[row][col] = mat[row][col] / gcd
            
    resultDen = den / gcd
    return [result, resultDen]
def generate_public_key(bits_length=512, e=3):
    """
    产生关于 RSA 的合法参数, p, q, e
    :param bits_length: 所需的 p 和 q 要求的位长度
    :param e: 3
    :return: n, e
    """
    # 注意验证参数的合法性, 要求 phi(N) 与 e 互素
    while True:
        p = getPrime(bits_length)
        q = getPrime(bits_length)
        n = gmpy2.mpz(p) * gmpy2.mpz(q)
        phi_n = gmpy2.mpz(p - 1) * gmpy2.mpz(q - 1)

        if gmpy2.gcd(phi_n, e) == 1:
            return n, e
Example #25
0
def pollard_rho(n):
    """Pollard's rho method for small prime factor

    :param N: RSA public key N.
    """
    assert(has_gmpy2)
    x, y, d = 2, 2, 1
    while d == 1:
        x = g(x, n)
        y = g(g(y, n), n)
        d = gmpy2.gcd(x - y, n)

    if d != n:
        return d, n // d

    # Failed
    return None
Example #26
0
File: laba4.py Project: boggad/labs
def gen_keys():
    rs = gmpy2.random_state(hash(gmpy2.random_state()))
    P = gmpy2.mpz_urandomb(rs, mpz('256'))
    P = gmpy2.next_prime(P)
    Q = gmpy2.mpz_urandomb(rs, mpz('256'))
    Q = gmpy2.next_prime(Q)
    N = P*Q
    Fi = (P-1)*(Q-1)
    Pkey = gmpy2.mpz_random(rs, Fi)
    while not (gmpy2.gcd(Fi, Pkey) == 1):
        Pkey = gmpy2.mpz_random(rs, Fi)
    Skey = gmpy2.invert(Pkey, Fi)
    print('Публичный ключ: ')
    print(Pkey)
    print('Приватный ключ:')
    print(Skey)
    print('N:')
    print(N)
Example #27
0
def pollard_rho(n):
    """Pollard's rho method for small prime factor.

    :param N: number to factorize.
    """
    def g(x, n):
        return (x**2 + 1) % n

    x, y, d = 2, 2, 1
    while d == 1:
        x = g(x, n)
        y = g(g(y, n), n)
        d = gmpy2.gcd(x - y, n)

    if d != n:
        return d, n // d

    # Failed
    return None
Example #28
0
def parallel_invert(l, n):
    '''Inverts all elements of a list modulo some number, using 3(n-1) modular multiplications and one inversion.

Returns the list with all elements inverted modulo 3(n-1).'''
    l_ = l[:]
    for i in xrange(len(l) - 1):
        l[i + 1] = (l[i] * l[i + 1]) % n

    try:
        inv = invert(l[-1], n)
    except ZeroDivisionError:
        inv = 0
    if inv == 0:
        return gcd(l[-1], n)

    for i in xrange(len(l) - 1, 0, -1):
        l[i] = (inv * l[i - 1]) % n
        inv = (inv * l_[i]) % n
    l[0] = inv

    return l
Example #29
0
def p_sub_1_attack(n, e):
    DIFFICULTY1, TRIAL_NUM = 20, 100
    A = 1 << DIFFICULTY1
    PrimesTable = Generate_PrimeTable_Sieve(A)
    r = []
    for prime in PrimesTable:
        a = math.floor(math.log(A, prime))
        r.append(prime**a)
    p, q = 0, 0
    for _ in range(TRIAL_NUM):
        base = PrimesTable[random.randint(0, len(PrimesTable) - 1)]
        x = base
        for pa in r:
            x = pow(x, pa, n)
        if x != 1:
            p = gmpy2.gcd(x - 1, n)  # p = gcd(x-1,n)
            q = n // p  # q = n / p
            break
    phi = (p - 1) * (q - 1)
    d = gmpy2.invert(e, phi)
    return p, q, d
Example #30
0
def pollardRho(n):
    n = mpz(n)
    i = mpz(1)
    x = randint(0, (n-1))
    y = x
    k = mpz(2)
    while True:
        i = i +1
        x = pow(x,2,n) -1 % n
        if(x < 0):
            x = n -1
        d = gcd((y-x),n)
        if(d != 1 and d != n):
            print "The factor is: "
            print d
            print "And "
            print n/d
            return True
        if i == k:
            y = x
            k = 2*k
Example #31
0
def rsaEncode(msg):
    f=open("out","a")
    while True:
        ran=random.randint(3, 12)
        if isPrime(ran):
            break
    e=ran*getPrime(30)
    p = getPrime(1024)
    q = getPrime(1024)
    while (not gmpy2.gcd((p-1)*(q-1),e)==ran or p*q<pow(msg,ran)):
        p = getPrime(1024)
        q = getPrime(1024)
    n=p*q
    assert(pow(msg,ran)<n)
    print("rsaEncode_init_finish!")
    dsaEncode(p)
    f.write("rsaEncode n:"+hex(n)+"\n")
    f.write("rsaEncode e:"+hex(e)+"\n")
    c=pow(msg,e,n)
    f.write("rsaEncode flag is:"+hex(c)+"\n")
    f.close()
def computeRight(x,y, MAX):
  # find how many. how many points on line O-P are ints?
  # then project them from P to Q until reaching MAX x
 
#(2,3) -> each 3 righ -> (2+3,3-2), (2+2*3,3-2*2)
#(4,6) -> [gcd] (2,3) -> each 3 right
#(2,2) -> gcd - 1,1 -> each 1 right/down -> (1+1, 1-1), inv(1+2*1, 1-2*1), ..
#(3,2) -> each 3 down - inv(3+2,2-3), inv(3+2*2, 2-2*3)
#(6,4) -> gcd (3,2)each 3 down - (6+2,4-3), inv(6+2*2,4-2*3),

    # direction to go on second side
    dx = y
    dy = x
    gcd = int(gmpy2.gcd(x,y))
    if gcd > 1:
       dx = dx // gcd
       dy = dy // gcd

    sx = (MAX - x) // dx
    sy = y // dy
    return min(sx, sy)
Example #33
0
 def attack(self, publickey, cipher=[], progress=True):
     """Run tests against fermat composites"""
     with timeout(self.timeout):
         try:
             limit = 10000
             p = q = None
             for x in tqdm(range(1, limit), disable=(not progress)):
                 f = (2 ** 2 ** x) + 1
                 fermat = gcd(f, publickey.n)
                 if 1 < fermat < publickey.n:
                     p = publickey.n // fermat
                     q = fermat
                     break
             if p is not None and q is not None:
                 priv_key = PrivateKey(
                     int(p), int(q), int(publickey.e), int(publickey.n)
                 )
                 return (priv_key, None)
             return (None, None)
         except TimeoutError:
             return (None, None)
Example #34
0
def attack(e, n):
    # Take a shitty message
    m = 7
    # m = hex(m)[2:]

    r.sendline(hex(m)[2:])
    data = r.recv().decode().strip().split('\n\n')
    c = data[0].split(': ')[1]
    # print(data)
    # print(c)
    c = int(c, 16)

    p = gmpy2.gcd(pow(c, e, n) - m, n)
    # print(p)
    q = n // p
    if q != 1:  # q == 1 means secure encryption no attack possible
        phi = (p - 1) * (q - 1)
        d = gmpy2.invert(e, phi)
        return d
    else:
        return 0
Example #35
0
File: pyecm.py Project: zardus/blob
def parallel_invert(l, n):
    """Inverts all elements of a list modulo some number, using 3(n-1) modular multiplications and one inversion.

Returns the list with all elements inverted modulo 3(n-1)."""
    l_ = l[:]
    for i in xrange(len(l) - 1):
        l[i + 1] = (l[i] * l[i + 1]) % n

    try:
        inv = invert(l[-1], n)
    except ZeroDivisionError:
        inv = 0
    if inv == 0:
        return gcd(l[-1], n)

    for i in xrange(len(l) - 1, 0, -1):
        l[i] = (inv * l[i - 1]) % n
        inv = (inv * l_[i]) % n
    l[0] = inv

    return l
Example #36
0
    def generate(self, bits, k=999):
        """
        Return public and private key of RSA
        :param bits: minimum number of bits for p and q
        :param k: number of checks in miller_rabin algorithm
        """
        p = q = 0
        while True:
            p = rand_n_bits_number(bits)
            if is_prime_miller_rabin(p, k):
                break

        # every 24 bits, about 7 digits difference - rand between 14 and 42 digits difference
        pq_bits_difference = random.randint(48, 144)
        while True:
            q = rand_n_bits_number(bits + pq_bits_difference)
            if is_prime_miller_rabin(q, k):
                break
        n = gmpy2.mpz(p) * gmpy2.mpz(q)
        phi_n = gmpy2.mpz(p - 1) * gmpy2.mpz(q - 1)

        e = 0
        temp = rand_n_bits_number(16, even=True)
        while True:
            if gmpy2.gcd(temp, phi_n) == 1:
                e = gmpy2.mpz(temp)
                break
            temp += 1
        assert e < phi_n

        # ext = multiplicative_inverse(e, phi_n)
        ext = gmpy2.gcdext(e, phi_n)
        if ext[0] == 1:
            d = phi_n + ext[1]
        assert (d * e % phi_n == 1)

        self.private_key = (d, n)
        self.public_key = (e, n)

        return self.public_key, self.private_key
Example #37
0
    def find(self):
        i = 0
        while not self.kill.is_set():
            n, p, q = self.find_good_pair()
            t = n - (p + q - 1)
            e = EMIN
            while e < EMAX:
                if self.kill.is_set():
                    self.trials.put(i)
                    return
                i += 1
                o = make_onion(n, e)
                if self.matches_regex(o.decode('utf-8')) and gmpy2.gcd(e,
                                                                       t) == 1:
                    d = gmpy2.invert(e, t)
                    p = private_key(n, e, d, p, q)
                    self.results.put(o + p)
                    self.trials.put(i)
                    if self.one:
                        self.kill.set()

                e += 2
Example #38
0
def william_p1(n, process_id):
    # this algorithm technically works but literally none of the modulos were p+1 so idk
    # choose a B (work limit) to start with
    if gmpy2.bit_length(gmpy2.mpz(n)) <= 2044:
        work_limit = pow(n, (1 / 6))
    else:
        work_limit = gmpy2.div(n, 27)
    threshold = 3
    previous_sub2 = 2
    # A needs to be greater than 2 to start with so we therefore start with 3
    A = process_id + 3
    previous = A

    counter = 0
    # if the counter ever reaches m, terminate
    while counter != threshold:
        counter += 1
        # current = (a^(current-1) - current-2) % n)
        current = (((A**previous) - previous_sub2) % n)
        # move the previous variables forward
        previous_sub2 = previous
        previous = current

        d = gmpy2.gcd(current - 2, n)
        if d != 1 and d != n:
            # calculate the factorial of m
            mult = gmpy2.fac(threshold)
            if DEBUG:
                print(d, mult)
            # check to see if we've found the terminating conditions for p + 1
            if gmpy2.f_mod(mult, d):
                return d
        else:
            # increment threshold by 1 if we haven't found anything
            threshold += 1
        if threshold > work_limit:
            return 1

    return 1
Example #39
0
def pollard_p1(n, process_id):
    # choose a B (work limit) to start with
    if gmpy2.bit_length(gmpy2.mpz(n)) <= 2044:
        work_limit = pow(n, (1 / 6))
    else:
        work_limit = gmpy2.div(n, 27)
    a = 2
    # break up how many things we have to check so we can split over cores
    process_range = (math.floor(work_limit) // PROCESS_COUNT)
    start = process_range * process_id
    end = process_range * (process_id + 1) - 1

    # assign default values here so we are an excellent, coding standard following coder
    q1, q2, q3 = 0, 0, 0
    if DEBUG:
        # lock processes so we can print cleanly (thanks 421)
        processLock.acquire()
        print("CORE", process_id, "checking p1 from", start, "to", end)
        processLock.release()
        # calculate the quarter ranges
        q1 = ((process_range // 4) * 1) + start
        q2 = ((process_range // 4) * 2) + start
        q3 = ((process_range // 4) * 3) + start
    for i in range(start, end):
        # print informative debug statements
        if DEBUG:
            if i == q1:
                print("CORE", process_id, "p1 25%")
            elif i == q2:
                print("CORE", process_id, "p1 50%")
            elif i == q3:
                print("CORE", process_id, "p1 75%")

        # check to see if we've found the terminating conditions for p - 1
        a = gmpy2.powmod(a, i, n)
        d = gmpy2.gcd(a - 1, n)
        if d != 1 and d != n:
            return d
    return 1
Example #40
0
    def encrypt(m, n, g):
        """
        Encrypts a message, given a public key.
        
        Parameters:
            m: number to be encrypted
            n,g: public keys used for the decryption
        Returns:
            c: encrypted representation of m
        """
        n2 = pow(n, 2)
        one = gmpy2.mpz(1)
        state = gmpy2.random_state(int_time())
        r = gmpy2.mpz_random(state, n)
        while gmpy2.gcd(r, n) != one:
            state = gmpy2.random_state(int_time())
            r = gmpy2.mpz_random(state, n)

        x = gmpy2.powmod(r, n, n2)
        c = gmpy2.f_mod(gmpy2.mul(gmpy2.powmod(g, m, n2), x), n2)

        return c
Example #41
0
def rsaEncode2(m):
    m=int.from_bytes(m.encode(),'big')
    f=open("out","w")
    while True:
        ran=random.randint(20, 50)
        if isPrime(ran):
            break
    e=ran*getPrime(30)
    p = getPrime(1024)
    q = gmpy2.next_prime(p)
    while (not gmpy2.gcd((p-1)*(q-1),e)==ran or p*q>pow(m,ran)):
        p = getPrime(1024)
        q = gmpy2.next_prime(p)
    n=p*q
    assert(pow(m,ran)>n)
    c=pow(m,e,n)
    f.write("n2:"+hex(n)+"\n")
    f.write("e2:"+hex(e)+"\n")
    f.write("rsaEncode2 re is:"+hex(c)+"\n")
    f.close()
    print("rsaEncode2_finish!")
    return pow(m,ran,n)
Example #42
0
def solve_bounty(x, challenge_no, challenge, a0, incorrect_root = False, incorrect_hash_to_prime = False, not_prime = False):
    p = hash_to_prime(x, incorrect_hash_to_prime)
    if not_prime:
        multiplicative_group_order = reduce(mul, [x - 1 for x in challenge["factors"]])
        while is_prime(p) or gcd(p, multiplicative_group_order) > 1:
            p += 2
    y = modular_root(challenge["modulus"], challenge["factors"], x, p)

    if incorrect_root:
        y += 1
    else:
        assert powmod(y, p, challenge["modulus"]) == x

    xbytes = x.to_bytes(((x.bit_length() + 7) // 8) * 1, "big")
    ybytes = y.to_bytes(((y.bit_length() + 7) // 8) * 1, "big")

    bytes_to_hash = challenge_no.to_bytes(32, "big") + xbytes + \
                    ybytes + \
                    p.to_bytes(32, "big") + \
                    bytes.fromhex(a0[2:]).rjust(32, b"\0")
    
    return y, p, xbytes, ybytes, bytes_to_hash
def genkey():
    while 1:
        while 1:
            p = getPrime(512)
            q = getPrime(512)
            if len(bin(abs(p - q))[2:]) < 450 or (p + q) & 1 != 0:
                continue

            phi = (p - 1) * (q - 1)
            e = 257
            print (gmpy2.gcd(phi, e))
            try:
                d = int(gmpy2.invert(e, phi))
            except:
                continue

            assert (d * e) % phi == 1
            ret = (d*e - 1) // phi
            break

        print ('d : ', d)
        r = 256
        mod = 2 ** r
        d0 = d % mod

        d0e = d0 * e
        print (bin(d0e)[-10:])

        if d0e & (1 << 2):
            x = RSA.construct((p*q, e, d, p, q))
            output = x.exportKey("PEM")
            with open('pri.pem', 'w') as f:
                f.write(output)
            output = x.publickey().exportKey("PEM")
            with open('pub.pem', 'w') as f:
                f.write(output)
            break
    return ret
Example #44
0
def affine_enc(m, *k):
    """
        Do affine cipher encryption.
        compute ci ≡ ami + b (mod 26)

    :param str m: Plaintext. It consists of lowercase letter and space,comma ....
    :param tuple k: Key.  k = (a,b). Note that a and 26 must be coprime
    :return str c:
    """
    a = k[0]
    b = k[1]
    assert 0 < a < 26
    assert 0 <= b < 26
    assert gcd(a, 26) == 1

    c = ""
    for i in range(len(m)):
        if m[i].isalpha():
            c[i] = chr((a * (ord(m[i]) - 97) + b) % 26 + 97)
        else: # if m[i] is a space or sthg
            c[i] = m[i]

    return m
Example #45
0
def affine_dec(c, *k):
    """
        ci ≡ ami + b (mod 26)  =>
        mi ≡ a^(-1) * (ci-b) (mod 26)

    :param str c: Ciphertext.
    :param tuple k: Same as above
    :return str m:
    """
    a = k[0]
    b = k[1]
    assert 0 < a < 26
    assert 0 <= b < 26
    assert gcd(a, 26) == 1

    m = ""
    for i in range(len(c)):
        if c[i].isalpha():
            m[i] = chr(invert(a) * (ord(c[i]) - 97 - b) % 26 + 97)
        else: # if m[i] is a space or sthg
            m[i] = c[i]

    return m
Example #46
0
    def pollard_P_1(self, n, progress=True):
        """Pollard P1 implementation"""
        z = []

        def first_primes(n):
            p = 2
            tmp = [p]
            while p <= n - 1:
                p = next_prime(p)
                tmp.append(p)
            return tmp

        prime = first_primes(997)
        logn = math.log(int(isqrt(n)))

        for j in range(0, len(prime)):
            primej = prime[j]
            logp = math.log(primej)
            for i in range(1, int(logn / logp) + 1):
                z.append(primej)

        try:
            for pp in tqdm(prime, disable=(not progress)):
                i = 0
                x = pp
                while 1:
                    x = powmod(x, z[i], n)
                    i = i + 1
                    y = gcd(n, x - 1)
                    if y != 1:
                        p = y
                        q = n // y
                        return p, q
                    if i >= len(z):
                        return 0, None
        except TypeError:
            return 0, None
Example #47
0
def my_rsa_key_generator(nbits):
  pattern_size = 256 
  prime_size = nbits // 2

  pattern = gmpy2.mpz(random.getrandbits(pattern_size))
  pattern = pattern.bit_set(pattern_size - 1)
  pattern = pattern.bit_set(pattern_size - 2)
  p = pattern
  while p.bit_length() != prime_size:
    p = pattern + (p << pattern_size)

  # To make it harder we change MSB and LSB, so one shouldn't assume
  # are also patterns.
  msb = 8*6
  lsb = 8*10

  p = p & (2**(prime_size - msb) - 1)
  p = random.getrandbits(msb)*(2**(prime_size - msb)) + p
  p = p.bit_set(prime_size - 1)
  p = p.bit_set(prime_size - 2)

  p = p >> lsb 
  p = p << lsb
  p += random.getrandbits(lsb)
  p = gmpy2.next_prime(p)

  q = gmpy2.mpz(random.getrandbits(prime_size))
  q = q.bit_set(prime_size - 1)
  q = q.bit_set(prime_size - 2)
  q = gmpy2.next_prime(q)

  e = 0x10001
  n = p*q
  lcm = (p-1)*(q-1) // gmpy2.gcd(p-1, q-1)
  d = gmpy2.invert(e, lcm)

  return list(map(int, [n, e, d, p, q]))
Example #48
0
def cal_p(A, B):
    x1, y1 = A
    x2, y2 = B
    return gcd(pow(x1, 2) + pow(y1, 2) - 1, pow(x2, 2) + pow(y2, 2) - 1)
Example #49
0
def phi(k):
    ret = 0
    for e in range(1, k + 1):
        if gmpy2.gcd(e, k) == 1:
            ret += 1
    return ret
Example #50
0
def gcd(a, b):
    return gmpy2.gcd(a, b)
Example #51
0
def big_num():
    operator = request.values.get('operator')
    result = '1'

    try:
        if operator == 'FACT' or operator == 'isPrime':
            p = gmpy2.mpz(int(request.values.get('p')))
            if not p:
                resu = {'code': 10001, 'message': '参数不能为空!'}
                return json.dumps(resu, ensure_ascii=False)
            if operator == 'FACT':  #p的阶层
                result = gmpy2.fac(p)
            elif operator == 'isPrime':  #判断p是否是素数
                result = gmpy2.is_prime(p)
        elif operator == 'MULMN' or operator == 'POWMN':
            p = gmpy2.mpz(int(request.values.get('p')))
            q = gmpy2.mpz(int(request.values.get('q')))
            n = gmpy2.mpz(int(request.values.get('n')))
            if not p and not q and not n:
                resu = {'code': 10001, 'message': '参数不能为空!'}
                return json.dumps(resu, ensure_ascii=False)
            if operator == 'POWMN':  #计算p**q mod n
                result = gmpy2.powmod(p, q, n)
            elif operator == 'MULMN':  #计算p*q mod n
                result = gmpy2.modf(gmpy2.mul(p, q), n)
        else:
            p = gmpy2.mpz(int(request.values.get('p')))
            q = gmpy2.mpz(int(request.values.get('q')))
            if not p and not q:
                resu = {'code': 10001, 'message': '参数不能为空!'}
                return json.dumps(resu, ensure_ascii=False)
            if operator == 'ADD':  #相加
                print('good')
                result = gmpy2.add(p, q)
            elif operator == 'SUB':  #相减
                result = gmpy2.sub(p, q)
            elif operator == 'MUL':  #相乘
                result = gmpy2.mul(p, q)
            elif operator == 'DIV':  #相除
                result = gmpy2.div(p, q)
            elif operator == 'MOD':  #取余
                result = gmpy2.f_mod(p, q)
            elif operator == 'POW':
                result = gmpy2.powmod(p, q)
            elif operator == 'GCD':  #最大公因数
                result = gmpy2.gcd(p, q)
            elif operator == 'LCM':
                result = gmpy2.lcm(p, q)
            elif operator == 'OR':  #或
                result = p | q
            elif operator == 'AND':  #与
                result = p & q
            elif operator == 'XOR':  #抑或
                result = p ^ q
            elif operator == 'SHL':  #左移
                result = p << q
            elif operator == 'SHR':  #右移
                result = p >> q
        resu = {'code': 200, 'result': str(result)}
        return json.dumps(resu, ensure_ascii=False)
    except:
        resu = {'code': 10002, 'message': '异常。'}
        return json.dumps(resu, ensure_ascii=False)
Example #52
0
jks0_input = ".".join(jwt0.split('.')[0:2])
sha256_0 = SHA256.new(jks0_input.encode('ascii'))
padded0 = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(sha256_0, len(jwt0_sig_bytes))

jks1_input = ".".join(jwt1.split('.')[0:2])
sha256_1 = SHA256.new(jks1_input.encode('ascii'))
padded1 = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(sha256_1, len(jwt0_sig_bytes))

m0 = bytes2mpz(padded0)
m1 = bytes2mpz(padded1)

pkcs1 = asn1tools.compile_files('data/pkcs1.asn', codec='der')
x509 = asn1tools.compile_files('data/x509.asn', codec='der')

for e in [mpz(3), mpz(65537)]:
    gcd_res = gcd(pow(jwt0_sig, e) - m0, pow(jwt1_sig, e) - m1)
    #To speed things up switch comments on prev/next lines!
    #gcd_res = mpz(0x143f02c15c5c79368cb9d1a5acac4c66c5724fb7c53c3e048eff82c4b9921426dc717b2692f8b6dd4c7baee23ccf8e853f2ad61f7151e1135b896d3127982667ea7dba03370ef084a5fd9229fc90aeed2b297d48501a6581eab7ec5289e26072d78dd37bedd7ba57b46cf1dd9418cd1ee03671b7ff671906859c5fcda4ff5bc94b490e92f3ba9739f35bd898eb60b0a58581ebdf14b82ea0725f289d1dac982218d6c8ec13548f075d738d935aeaa6260a0c71706ccb8dedef505472ce0543ec83705a7d7e4724432923f6d0d0e58ae2dea15f06b1b35173a2f8680e51eff0fb13431b1f956cf5b08b2185d9eeb26726c780e069adec0df3c43c0a8ad95cbd342)
    print("[*] GCD: ", hex(gcd_res))
    for my_gcd in range(1, 100):
        my_n = c_div(gcd_res, mpz(my_gcd))
        if pow(jwt0_sig, e, my_n) == m0:
            print("[+] Found n with multiplier", my_gcd, " :\n", hex(my_n))
            pkcs1_pubkey = pkcs1.encode("RSAPublicKey", {
                "modulus": int(my_n),
                "publicExponent": int(e)
            })
            x509_der = x509.encode(
                "PublicKeyInfo", {
                    "publicKeyAlgorithm": {
                        "algorithm": "1.2.840.113549.1.1.1",
Example #53
0
import gmpy2
N1 = 3895738302299059518129198422310169628530536557191890566210939781698372336257482186582163630847612416277492034959243510457939210010336159061758606919109259916143600981918456942199762738624796190838889500238780675229383463267807384154074134251073572174392024892486431125499446924573006208711810847272390619510395812856188247531815920797526102562723333957594242603466996229335924848954210939152042149332307810693239925149256224795031982752752336401872520016106145667479144091130160998875256860809091721275069193773739370057334041922519998813268278574260846083883264261920589114740823464192397850923545998904365370408113

N2 = 3036683903819675505741091164945461947189004916494633766372176282409409694958701211748277050499101511956962003835932755555293255586827283990400451317444723234406968971873530093281591689832798646915816609347861047534121792409030834659241904646743453387504496246791081682741245482378149293399372654558929658582070853972454887854658545741800574343930155288517185535533201220281739954820271979667081052363406511938025061398551356675540358212449132781674832812796443378476387659729623581274433769056775163718782871879747276327458473970177451591251859530403032170215968101310739004163533767679394201611410832974546802038041

N3 = 4793455677299549137382284585015750073239112414361680529255951318217960300841340399094743130287927996565298160174555422185410320841942637374406558835150138631140265626020072464652973386772727192540062051929655235552439145036105501434801984612127808829810146844869487529177642676245549299371487478280457673839725488195812744535928488844735950540356920273038857127652414836352483913807655170699520816765863272825856765769043174406026964068017257738085400965661973681558654658747878342173984592411085018242201038877382766239487564503728442821348064764166024851080258629751476765613997512620274759264076272801682962144457

E = 65537

C1 = 396708474546125804352894757436683688457291028695044217325853929491171136935487190613513217479209066321213697066977005912522338337419604329864854419961723570625025089500459612736934675744115710978556346050350466970024450696226499749911198313775828281699871502987873199226066403667788132060336882800770615332190939846610876881382430101512212915247532319827304296610854802037475047119525110795533529161852951539770153761419387662527094415537933400873451490021233979268224054475360645920086811082803271848565851436058022797610887635287190533293980480191482625531855511415716253479184799509403767653927424232672209598509

C2 = 355006513750551550798931713354683491263062473879176656452255051848683497534660576981575518851351256702360823676609578259232763677292692743319345273559085724516350773319337226043634439282120083618718026203533033564167432280901197175559735572797382863132012675404876908914335941746393221402727788260354881773319480220225939283398326940847106630716629330817737251316474369640273632208347751866683363389016722969822345738247486942531821199790024647950924227337611907877819668593060172268197128413003269501597578146759488894526193598933152416894414296396043283131502951693668167550687432080480619240585408701379144341703

C3 = 924835278307680480966328618545268895077532556525413716080960421925985654497130329688156219485942736928562517552888163928270855659413958949301590302010862666331053838345196518237383846281768395909801043955047640003147798786793258813501366000503338638933238548605016169865688228297750780710248359326295693845663887055907900967535999885217905972006140096240831305484619796964713673839223632057905454213937054336962510051529266336629730913756688411854427999570223208667606703681762027957427028839409594591627448224813082072169775916331655060221445546199171668136050686471357710989346885039441000083764142021784018773006

q = gmpy2.gcd(N1, N2)
r = gmpy2.gcd(N2, N3)
p = gmpy2.gcd(N3, N1)

phi1 = (p - 1) * (q - 1)
phi2 = (q - 1) * (r - 1)
phi3 = (r - 1) * (p - 1)

d1 = gmpy2.invert(E, phi1)
d2 = gmpy2.invert(E, phi2)
d3 = gmpy2.invert(E, phi3)

m1 = pow(C1, d1, N1)
m2 = pow(C2, d2, N2)
m3 = pow(C3, d3, N3)
Example #54
0
p1 = 282595361018796512312481928903796535047168039821441204226899357708165480989181288601210607191471483534037953052604722708819774231230476577951670676743338887609132820418468389978419501153422449272224388422022777
q1 = 142270506848638924547091203976235495577725242858694711068289574174127601000137457280276860615471044907560710121669055364010408768146949985099404319539891688093875478389341632242096859500255283810703767020918479
k = 877
p2 = 291668652611471250039066078554824884845341136873092210122454888337748213391694969640183343019452438800975699247613989121123985462360872265327833435184781051854777074884190706087067889456284908187292126902073849
q2 = 90298557884682577669238320760096423994217812898822512514104930945042122418007925771281125855142645396913218673571816112036657123492733042972301983242487835472292994595416656844378721884370309120262139835889657
k = 1041
p3 = 267307309343866797026967908679365544381223264502857628608660439661084648014195234872217075156454448820508389018205344581075300847474799458610853350116251989700007053821013120164193801622760845268409925117073227
p4 = 188689169745401648234984799686937623590015544678958930140026860499157441295507274434268349194461155162481283679350641089523071656015001291946438485044113564467435184782104140072331748380561726605546500856968771

f = open("output.txt", "r")
data = f.read().split("\n")
for i in range(4):
    data[i] = map(int, data[i].split(" ")[1:])
e = 1667

r = gcd(data[1][0], data[0][0])
d2 = invert(e, (p1 - 1) * (q1 - 1) * (r - 1))
print data[1][0] % q1
d1 = invert(e, (p2 - 1) * (q2 - 1) * (r - 1))

print data[2][0] % (p3**2)
q3 = data[2][0] / (p3**2)
d3 = invert(e, (p3 - 1) * p3 * (q3 - 1))
q4 = data[3][0] / p4
assert data[3][0] == p4 * q4
d4 = invert(e, (p4 - 1) * (q4 - 1))
c = 594744523070645240942929359037746826510854567332177011620057998249212031582656570895820012394249671104987340986625186067934908726882826886403853350036347685535238091672944302281583099599474583019751882763474741100766908948169830205008225271404703602995718048181715640523980687208077859421140848814778358928590611556775259065145896624024470165717487152605409627124554333901173541260152787825789663724638794217683229247154941119470880060888700805864373121475407572771283720944279236600821215173142912640154867341243164010769049585665362567363683571268650798207317025536004271505222437026243088918839778445295683434396247524954340356
c = pow(c, d4, data[3][0])
c = pow(c, d3, data[2][0])
c = pow(c, d2, data[1][0])
c = pow(c, d1, data[0][0])
Example #55
0
from gmpy2 import gcd, invert, powmod
from Crypto.Util.number import long_to_bytes

n1 = 14343453794367092515497895137902168386296417319247146730459319881802140334698737189342973812146465828660342012946910653192803473600595707696472591504951198563603709181626005658184116684367802758344031386496658458264959969692044879175628783605186867276515694784082482043436473458055894723810140516689141599152195984714148210638833797638255124702611899073506190942745515704802064433300261613781916198106074829630095538317067848424354570246167013526201728488570271571071978289748473886089178585249674489547064957622989808178007470483946536987289341591847349128538928294808117443145097551386826012131775390678998400121889
n2 = 20308195943065789251817446829863883469272602304751753219641822206296872340042055615695828234875654938558065292577939692476866300109337008636927498617655004089261030659132847752508448477243753135984370110439693105967818735745420000128069178972088161949286955900852997852216281385776262449633762670014571643311788609943581805728189446261833834354199480558854660930835489848639377800962143545608517015172667287024378681310097239827666867592226542748876958241795640727126418223939447294264460580825913526549434716100031432143671503937393640601052321015919112419872256052688412078974604159554387677255024728801489704260363
c1 = 7060913174371289769309763235647638447135191122575239829016360331184038730172940927388867110734381358453407989806140634011350721798160713053621896705641720212112551788757319365520015847374673960320334248580560205413153114427654784961710348834514336159373193900583620653085765067165174133038800649323672785585501521017885631280303551697739951014696330327670228229605047676440962916067564193271247936974843751339372847625153953559941840547748375919498892051841063000432368600158512968060459462404612866403066205167176313042517873197370743936042865113128112591367582742396193149320607077649094903691975739181219359076265
c2 = 20148610260208170593289118672038891818770076647095364134619069654881479351996793675661468921299369828610961411535098751945943055486021096222646490248098261096267277133140141311947840921090893680970207588861087220137922905797128028172779716663247976566807484416436273763735289602135279810958841816837092253309070217739840320870090502512130142015671736882941916450932012952894134313348115440744061809508935802755106889882605495521669026118538807594430799171795521056652204797565525565412195933084030518258900930049905119086640401568596910662117008862676917676436361632490924908191898958534522611573541581472875515834526
e = 65537
p = gcd(n1, n2)
q1 = n1 // p
phi = (p - 1) * (q1 - 1)
d = invert(e, phi)
m = powmod(c1, d, n1)
flag = long_to_bytes(m)
print(flag.decode())
Example #56
0
            if 1.0 * A1 / A2 == comp_jk:
                result[A1] = A2
            if 1.0 * A3 / A4 == comp_jk:
                result[A3] = A4
            if 1.0 * A1 / A4 == comp_jk:
                result[A1] = A4
            
            if 1.0 * A1 / A5 == comp_ik:
                result[A1] = A5
            if 1.0 * A3 / A5 == comp_ik:
                result[A3] = A5
            if 1.0 * A1 / A6 == comp_ik:
                result[A1] = A6
            
            if 1.0 * A2 / A6 == comp_ij:
                result[A2] = A6
            if 1.0 * A2 / A5 == comp_ij:
                result[A2] = A5
            if 1.0 * A4 / A6 == comp_ij:
                result[A4] = A6

numerator = 1
denominator = 1

for key in result.keys():
    numerator *= key
    denominator *= result[key]

print denominator / gmpy2.gcd(numerator, denominator)
Example #57
0
def nc_are_prime(n, c):
    if not all([n, c]):
        return
    gcd = gmpy2.gcd(n, c)
    if gcd != 1:
        print('n, c not prime, gcd is ', gcd)
Example #58
0
t = next_prime(o)
u = next_prime(s)
print o * s
n2 = o * s * t * u
assert (m < n2)
print n2
c2 = pow(m, e, n2)
## level3
m = c2
p = getPrime(800)
q = getPrime(800)

n3 = p * q
phi = (q - 1) * (p - 1)
assert (m < n3)
print n3
while True:
    s = getPrime(10)
    if (gcd(s, p - 1) == 1):
        sinv = invert(s, p - 1)
        e = 4 * s * sinv + 3
        if (gcd(phi, e) == 1):
            break
c3 = pow(m, e, n3)
print c3
m = bytes_to_long(os.urandom(128))

print m
assert (m < n3)
print pow(m, e, n3)
Example #59
0
import gmpy2
import binascii

n = 15944475431088053285580229796309956066521520107276817969079550919586650535459242543036143360865780730044733026945488511390818947440767542658956272380389388112372084760689777141392370253850735307578445988289714647332867935525010482197724228457592150184979819463711753058569520651205113690397003146105972408452854948512223702957303406577348717348753106868356995616116867724764276234391678899662774272419841876652126127684683752880568407605083606688884120054963974930757275913447908185712204577194274834368323239143008887554264746068337709465319106886618643849961551092377843184067217615903229068010117272834602469293571
e1 = 797
c1 = 11157593264920825445770016357141996124368529899750745256684450189070288181107423044846165593218013465053839661401595417236657920874113839974471883493099846397002721270590059414981101686668721548330630468951353910564696445509556956955232059386625725883038103399028010566732074011325543650672982884236951904410141077728929261477083689095161596979213961494716637502980358298944316636829309169794324394742285175377601826473276006795072518510850734941703194417926566446980262512429590253643561098275852970461913026108090608491507300365391639081555316166526932233787566053827355349022396563769697278239577184503627244170930

e2 = 521
c2 = 6699274351853330023117840396450375948797682409595670560999898826038378040157859939888021861338431350172193961054314487476965030228381372659733197551597730394275360811462401853988404006922710039053586471244376282019487691307865741621991977539073601368892834227191286663809236586729196876277005838495318639365575638989137572792843310915220039476722684554553337116930323671829220528562573169295901496437858327730504992799753724465760161805820723578087668737581704682158991028502143744445435775458296907671407184921683317371216729214056381292474141668027801600327187443375858394577015394108813273774641427184411887546849

assert gmpy2.gcd(e1, e2) == 1
s = gmpy2.gcdext(e1, e2)
m1 = gmpy2.powmod(c1, s[1], n)
m2 = gmpy2.powmod(c2, s[2], n)

m = (m1 * m2) % n

print(binascii.unhexlify(hex(m)[2:]))


# method
def common_modulus(n, c1, e1, c2, e2):
    s = gmpy2.gcdext(e1, e2)
    m1 = gmpy2.powmod(c1, s[1], n)
    m2 = gmpy2.powmod(c2, s[2], n)
    m = (m1 * m2) % n
    unhexlify = binascii.unhexlify(hex(m)[2:])
    print(unhexlify)
    return unhexlify
 def gen_coprime(self, x):
     while True:
         random_state = gmpy2.random_state(int(time.time() * 100000))
         coprime = gmpy2.mpz_random(random_state, x)
         if gmpy2.gcd(coprime, x) == 1:
             return coprime