Beispiel #1
0
def solver(N1_, N2_):
    N1 = mpz(N1_)
    N2 = mpz(N2_)
    common_p = gcd(N1, N2)
    q1 = gmpy2.c_div(N1, common_p)
    q2 = gmpy2.c_div(N2, common_p)
    return (common_p, q1, q2)
    def key_from_sig(self) -> (int, int):
        """
        gcd(c1**e - m1, c2**e - m2, cn**e - mn) as described in:
        https://crypto.stackexchange.com/questions/30289/is-it-possible-to-recover-an-rsa-modulus-from-its-signatures/30301#30301
        And expanded on in:
        https://crypto.stackexchange.com/questions/33642/given-enough-rsa-signature-values-is-it-possible-to-determine-the-public-key-va
        """
        # Check if signature lengths match.
        if len({len(i) for i in self.token_list}) != 1:
            Exception("Token signatures are not all the same length!")

        for e in self.exponent:
            ti = []
            for checksum in self.token_list:
                ti.append(
                    pow(mpz(int(self.token_list[checksum], 16)), mpz(e)) -
                    mpz(int(checksum, 16)))
            N = reduce(lambda x, y: gcd(x, y), ti)
            # If the N is too short, say 1 or 2, this cannot be correct.
            if N.bit_length() > 100:
                checksum = random.choice(list(self.token_list))
                for i in range(1, 100):
                    # Verify N
                    if pow(int(self.token_list[checksum], 16), e,
                           c_div(N, mpz(i))) == int(checksum, 16):
                        n = int(c_div(N, mpz(i)))
                        return e, n
        return None, None
    def _step2c_searching_with_one_interval_left(self):
        ## this is the hardest one.
        # You need to get the most recent interval set from M,
        # and then get the first interval of that set. Unpack
        # the interval tuple to variables a, b
        most_recent_interval_set = self.M[-1]
        (a, b) = most_recent_interval_set[0]
        # Next, compute ri = (2(b x s[-1] - 2B))/self.n
        #    (use gmpy2.c_div for these computations)
        div_ri = 2 * ((b * self.s[-1]) - self.B * 2)
        ri = gmpy2.c_div(div_ri, self.n)
        # Finally, search for an s between (2B+(ri x n))/b
        #   and (3B+(ri x n))/a

        low = gmpy2.f_div((self.B * 2 + (ri * self.n)), b)
        high = gmpy2.c_div((self.B * 3 + (ri * self.n)), a)
        si = self._find_s(low, high)
        #
        # If no si is found, increase ri by one and try again.
        while not si:
            ri += 1
            low = gmpy2.f_div((self.B * 2 + (ri * self.n)), b)
            high = gmpy2.c_div((self.B * 3 + (ri * self.n)), a)
            si = self._find_s(low, high)

        return si
 def _step2c_searching_with_one_interval_left(self):
     ## this is the hardest one.
     # You need to get the most recent interval set from M,
     # and then get the first interval of that set. Unpack
     # the interval tuple to variables a, b
     
     # Next, compute ri = (2(b x s[-1] - 2B))/self.n
     #    (use gmpy2.c_div for these computations)
     # 
     # Finally, search for an s between (2B+(ri x n))/b
     #   and (3B+(ri x n))/a
     # 
     # If no si is found, increase ri by one and try again.
     mostRecentInterval = self.M[-1][0]
     a,b = mostRecentInterval
     ri = (2 * (b * self.s[-1] - 2*self.B))
     ri = gmpy2.c_div(ri, self.n)
     si = None
     while si is None:
         start_s = 2 * self.B + (ri * self.n)
         start_s = gmpy2.c_div(start_s, b)
         s_max = 3 * self.B + (ri * self.n)
         s_max = gmpy2.c_div(s_max, a)
         si = self._find_s(start_s, s_max)
         ri += 1
     return si
 def _step2c_searching_with_one_interval_left(self):
     a,b = self.M[-1][0]
     ri = gmpy2.c_div(2*(b*self.s[-1] - 2*self.B),self.n)
     si = None
 
     while si == None:
         si = gmpy2.c_div((2*self.B+ri*self.n),b)
         
         s_max = gmpy2.c_div((3*self.B+ri*self.n),a) 
         si = self._find_s(start_s=si, s_max=s_max)
         ri += 1
     return si
Beispiel #6
0
def create_keypair(size):
    while True:
        p = get_prime(size // 2)
        q = get_prime(size // 2)
        if q < p < 2*q:   
            break

    N = p * q
    phi_N = (p - 1) * (q - 1)
   
    # Recall that: d < (N^(0.25))/3
    max_d = c_div(isqrt(isqrt(N)), 3)
    max_d_bits = max_d.bit_length() - 1

    while True:
        d = urandom.getrandbits(max_d_bits)
        try:
            e = int(gmpy2.invert(d, phi_N))
        except ZeroDivisionError:
            continue
        if (e * d) % phi_N == 1:
            break
    assert test_key(N, e, d)
    
    return  N, e, d, p, q
Beispiel #7
0
def create_keypair(size):
    while True:
        p = get_prime(size // 2)
        q = get_prime(size // 2)
        if q < p < 2 * q:
            break

    N = p * q
    phi_N = (p - 1) * (q - 1)

    # Recall that: d < (N^(0.25))/3
    max_d = c_div(isqrt(isqrt(N)), 3)
    max_d_bits = max_d.bit_length() - 1

    while True:
        d = urandom.getrandbits(max_d_bits)
        try:
            e = int(gmpy2.invert(d, phi_N))
        except ZeroDivisionError:
            continue
        if (e * d) % phi_N == 1:
            break
    assert test_key(N, e, d)

    return N, e, d, p, q
Beispiel #8
0
    def _step2c_searching_with_one_interval_left(self):
        ## this is the hardest one.
        # You need to get the most recent interval set from M,
        # and then get the first interval of that set. Unpack
        # the interval tuple to variables a, b

        # Next, compute ri = (2(b x s[-1] - 2B))/self.n
        #    (use gmpy2.c_div for these computations)
        #
        # Finally, search for an s between (2B+(ri x n))/b
        #   and (3B+(ri x n))/a
        #
        # If no si is found, increase ri by one and try again.
        si = None
        intervalSet = self.M[-1]
        interval = intervalSet[0]
        a, b = interval

        ri = gmpy2.c_div(2 * ((b * self.s[-1]) - (2 * self.B)), self.n) - 1
        while (si == None):
            bBound = (2 * self.B + (ri * self.n)) // b
            aBound = (3 * self.B + (ri * self.n)) // a
            si = self._find_s(bBound, aBound)
            ri += 1
        return si
Beispiel #9
0
 def _step2a_start_the_searching(self):
     # this function should return a found s where s starts
     # at n/3B. Because these are big numbers, you should use
     # gmpy2.c_div to divide n and 3B.
     # return the si found.
     si = gmpy2.c_div(self.n, 3 * self.B)
     return self._find_s(si)
Beispiel #10
0
def solve(*lines):
    P, Q = lines
    Q = mpz(Q)
    P = mpz(P)
    _gcd = gcd(P, Q)
    if gcd > 1:
        P = c_div(P, _gcd)
        Q = c_div(Q, _gcd)
    if not log2(Q).is_integer():
        return 'impossible'
    res = log2(P)
    res = mpz(floor(res))
    res, rem = c_divmod(Q, 2**res)
    if rem:
        return 'impossible'
    return int(log2(res))
 def _step3_narrowing_set_of_solutions(self, si):
     # This step reduces the number of possible solutions
     # It will start by iterating through all the Intervals in the
     #  most recent M. As you iterate through each Interval, unpack
     #  the Interval to variables a, b
     # 
     # For each interval a,b
     #    r_min is ((a x si) - 3B+1)/n (use gmpy2.c_div)
     #    r_max is ((b x si) - 2B)/n (use **gmpy2.f_div**)
     #    For r in range (r_min, r_max):
     #        new_a = (2B + (r x n))/ si (use gmpy2.c_div)
     #        new_b = ((3B-1) + (r x n))/si (use **gmpy2.f_div**)
     #        new_interval = Interval( max(a, new_a), min(b, new_b))
     #        add interval to a set of intervals
     
     # append the new intervals to M (the new last element of M will
     #   be the list of intervals discovered)
     # append si to self.s
     
     # IF the length of new intervals is 1 AND this single Interval's
     # a == b, return True, otherwise False
     
     # For explanations on why to use c_div vs f_div, look up these
     # functions in gmpy2 and then see if you can figure out why one is
     # used over the other
     mostRecentM = self.M[-1]
     intervals = []
     for a,b in mostRecentM:
         r_min = ((a * si) - 3 * self.B + 1) 
         r_min = gmpy2.c_div(r_min, self.n)
         r_max = ((b * si) - 2 * self.B)
         r_max = gmpy2.f_div(r_max, self.n)
         for r in range(r_min, r_max + 1):
             new_a = (2 * self.B + (r * self.n)) 
             new_a = gmpy2.c_div(new_a, si)
             new_b = ((3 * self.B-1) + (r * self.n))
             new_b = gmpy2.f_div(new_b, si)
             new_interval = Interval( max(a, new_a), min(b, new_b))
             intervals.append(new_interval)
     self.M.append(intervals)
     self.s.append(si)
     if len(intervals) == 1 and intervals[0].a == intervals[0].b:
         return True
     else:
         return False
    def _step3_narrowing_set_of_solutions(self, si):
        # This step reduces the number of possible solutions
        # It will start by iterating through all the Intervals in the
        #  most recent M. As you iterate through each Interval, unpack
        #  the Interval to variables a, b
        #
        most_recent_M = self.M[-1]
        new_intervals = []
        # For each interval a,b
        for interval in most_recent_M:
            (a, b) = interval
            #    r_min is ((a x si) - 3B+1)/n (use gmpy2.c_div)
            div_a = (a * si) - ((self.B * 3) - 1)
            r_min = gmpy2.c_div(div_a, self.n)
            #    r_max is ((b x si) - 2B)/n (use **gmpy2.f_div**)
            div_b = (b * si) - (self.B * 2)
            r_max = gmpy2.f_div(div_b, self.n)
            #    For r in range (r_min, r_max):
            for r in range(r_min, r_max + 1):
                #        new_a = (2B + (r x n))/ si (use gmpy2.c_div)
                div_new_a = (self.B * 2) + (r * self.n)
                new_a = gmpy2.c_div(div_new_a, si)
                #        new_b = ((3B-1) + (r x n))/si (use **gmpy2.f_div**)
                div_new_b = ((self.B * 3) + 1) + (r * self.n)
                new_b = gmpy2.f_div(div_new_b, si)
                #        new_interval = Interval( max(a, new_a), min(b, new_b))
                new_interval = Interval(max(a, new_a), min(b, new_b))
                #        add interval to a set of intervals
                new_intervals.append(new_interval)
        # append the new intervals to M (the new last element of M will
        #   be the list of intervals discovered)
        self.M.append(new_intervals)
        # append si to self.s
        self.s.append(si)

        # IF the length of new intervals is 1 AND this single Interval's
        # a == b, return True, otherwise False
        if len(new_intervals) == 1:
            (a, b) = new_intervals[0]
            if a == b:
                return True
        # For explanations on why to use c_div vs f_div, look up these
        # functions in gmpy2 and then see if you can figure out why one is
        # used over the other
        return False
 def _step2a_start_the_searching(self):
     # this function should return a found s where s starts
     # at n/3B. Because these are big numbers, you should use
     # gmpy2.c_div to divide n and 3B.
     # return the si found.
     start_s = gmpy2.c_div(self.n, self.B * 3)
     si = self._find_s(start_s)
     print("Found si: ", si)
     return si
    def _step3_narrowing_set_of_solutions(self, si):
        new_intervals = set()
        for a,b in self.M[-1]:
            r_min = gmpy2.c_div((a*si - 3*self.B + 1),self.n)
            r_max = gmpy2.f_div((b*si - 2*self.B),self.n)

            for r in range(r_min, r_max+1):
                a_candidate = gmpy2.c_div((2*self.B+r*self.n),si)
                b_candidate = gmpy2.f_div((3*self.B-1+r*self.n),si)

                new_interval = Interval(max(a, a_candidate), min(b,b_candidate))
                new_intervals.add(new_interval)
        new_intervals = list(new_intervals)
        self.M.append(new_intervals)
        self.s.append(si)
        
        if len(new_intervals) == 1 and new_intervals[0].a == new_intervals[0].b:
            return True
        return False
Beispiel #15
0
def main():

    guessnum = 512 - 16

    #   first make a dummy request to find the public modulus for our team
    initial_request = {"team": TEAM, "ciphertext": "00" * (n // 8)}
    r = requests.post(SERVER_URL + "/decrypt",
                      data=json.dumps(initial_request))
    try:
        N = int(r.json()["modulus"], 16)
    except:
        print(r.text)
        sys.exit(1)

    #   compute R^{-1}_N
    Rinv = gmpy2.invert(R, N)

    #   Start with a "guess" of 0, and analyze the zero-one gap, updating our
    #   guess each time. Repeat this for the (512-16) most significant bits of q
    g = gmpy2.mpz(0)

    for i in range(guessnum):  # used to be range(512 - 16)
        print(i)
        gap = compute_gap(g, i, Rinv, 50, N)

        #   TODO: based on gap, decide whether bit (512 - i) is 0 or 1, and
        #   update g accordingly
        if gap < 600:  # bit is 1
            g = g + 2**(512 - i)

    # Off-by-one error somewhere, and this line saves our ass somehow
    g = gmpy2.c_div(g, 2)

    # print("bin(g): ", str(bin(g)))

    # HARDCODED SOLUTION (used for testing purposes)
    # hs = int("0b11111000110110011111100101100001110010001001010010111010011100010110001010000001001001001010011111101110010111000011101011011111110010011111100100111011101001011100011110001111011011000011011111001111001011010100111110010110011010111001100110001100110110010110011111110010011111101001100100100001100000111111100010010001110111000000010000001001100010010000100100011100100100100100110111101011100101000000001011101111110101001100100001000110010101111101101011011100001001110010010010110001011010001000011000001001", 2)
    # hs_16_zeros = int("0b11111000110110011111100101100001110010001001010010111010011100010110001010000001001001001010011111101110010111000011101011011111110010011111100100111011101001011100011110001111011011000011011111001111001011010100111110010110011010111001100110001100110110010110011111110010011111101001100100100001100000111111100010010001110111000000010000001001100010010000100100011100100100100100110111101011100101000000001011101111110101001100100001000110010101111101101011011100001001110010010010110001011010000000000000000000", 2)
    # h = gmpy2.mpz(hs)
    # g = gmpy2.mpz(hs_16_zeros)
    # submit_guess(h)

    # brute-force last 16 bits
    print("Starting brute-force...")
    for i in range(2**16):
        q = g + i
        if N % q == 0:  # check if this is a valid q
            print("GOT EM")
            print(str(bin(q)))
            submit_guess(q)
Beispiel #16
0
def main():

    guessnum = 512-16

    #   first make a dummy request to find the public modulus for our team
    initial_request = {"team": TEAM, "ciphertext": "00"*(n//8)}
    r = requests.post(SERVER_URL + "/decrypt", data=json.dumps(initial_request))
    try:
        N = int(r.json()["modulus"], 16)
    except:
        print(r.text)
        sys.exit(1)

    #   compute R^{-1}_N
    Rinv = gmpy2.invert(R, N)

    #   Start with a "guess" of 0, and analyze the zero-one gap, updating our
    #   guess each time. Repeat this for the (512-16) most significant bits of q
    g = gmpy2.mpz(0)

    for i in range(guessnum): # used to be range(512 - 16)
        print(i)
        gap = compute_gap(g, i, Rinv, 50, N)

        #   TODO: based on gap, decide whether bit (512 - i) is 0 or 1, and
        #   update g accordingly
        if gap<600: # bit is 1
            g = g+2**(512-i)

    # Off-by-one error somewhere, and this line saves our ass somehow
    g = gmpy2.c_div(g, 2)

    # print("bin(g): ", str(bin(g)))

    # HARDCODED SOLUTION (used for testing purposes)
    # hs = int("0b11111000110110011111100101100001110010001001010010111010011100010110001010000001001001001010011111101110010111000011101011011111110010011111100100111011101001011100011110001111011011000011011111001111001011010100111110010110011010111001100110001100110110010110011111110010011111101001100100100001100000111111100010010001110111000000010000001001100010010000100100011100100100100100110111101011100101000000001011101111110101001100100001000110010101111101101011011100001001110010010010110001011010001000011000001001", 2)
    # hs_16_zeros = int("0b11111000110110011111100101100001110010001001010010111010011100010110001010000001001001001010011111101110010111000011101011011111110010011111100100111011101001011100011110001111011011000011011111001111001011010100111110010110011010111001100110001100110110010110011111110010011111101001100100100001100000111111100010010001110111000000010000001001100010010000100100011100100100100100110111101011100101000000001011101111110101001100100001000110010101111101101011011100001001110010010010110001011010000000000000000000", 2)
    # h = gmpy2.mpz(hs)
    # g = gmpy2.mpz(hs_16_zeros)
    # submit_guess(h)

    # brute-force last 16 bits
    print("Starting brute-force...")
    for i in range(2**16):
        q = g + i
        if N%q==0:    # check if this is a valid q
            print("GOT EM")
            print(str(bin(q)))
            submit_guess(q)
Beispiel #17
0
def safe_prime(exponent):
    for k in range(0,10000000):
        p = 10**exponent + k 

        # checks to see if p is prime
        a = gmpy2.powmod(2, p-1, p)

        if (a == 1): 
            # since p is prime, check to see if
            # p is a safe prime
            safe_p = gmpy2.c_div(gmpy2.sub(p,1),2)

            if (gmpy2.is_prime(int(safe_p))): 
                print "k = %i \nsafe prime = %i\n" % (k, safe_p)
                return
Beispiel #18
0
def safe_prime(exponent):
    for k in range(0, 10000000):
        p = 10**exponent + k

        # checks to see if p is prime
        a = gmpy2.powmod(2, p - 1, p)

        if (a == 1):
            # since p is prime, check to see if
            # p is a safe prime
            safe_p = gmpy2.c_div(gmpy2.sub(p, 1), 2)

            if (gmpy2.is_prime(int(safe_p))):
                print "k = %i \nsafe prime = %i\n" % (k, safe_p)
                return
Beispiel #19
0
def prim_root():

    # calls safe_prime func
    # and uses safe prime
    # for primitive root
    p = safe_prime(100)

    base = (2,3,5,7,11,13)
    
    for k in base:

        # checks to see if p is prime
        a = gmpy2.powmod(k, gmpy2.c_div(gmpy2.sub(p,1), 2), p)

        if (a != 1): 
            print "%i is a primitive root modulo     %i\n" % (k, p)
        
        else:
            print "%i is not a primitive root modulo %i\n" % (k, p)

    return
Beispiel #20
0
def findAVulnerablePrime(bitSize):
    generator = 65537
    m = nt.primorial(prime_default(bitSize), False)

    max_order = nt.totient(m)
    max_order_factors = nt.factorint(max_order)

    order = element_order_general(generator, m, max_order, max_order_factors)
    order_factors = nt.factorint(order)

    power_range = [0, order - 1]
    min_prime = g.bit_set(
        g.bit_set(g.mpz(0), bitSize // 2 - 1), bitSize // 2 - 2
    )  # g.add(pow(g.mpz(2), (length / 2 - 1)), pow(g.mpz(2), (length / 2 - 2)))
    max_prime = g.bit_set(
        min_prime, bitSize // 2 - 4
    )  # g.sub(g.add(min_prime, pow(g.mpz(2), (length / 2 - 4))), g.mpz(1))
    multiple_range = [g.f_div(min_prime, m), g.c_div(max_prime, m)]

    random_state = g.random_state(random.SystemRandom().randint(0, 2**256))

    return random_prime(random_state,
                        nt.primorial(prime_default(bitSize), False), generator,
                        power_range, multiple_range)
Beispiel #21
0
def create_dangerouse_keys(n_bits):
    while True:
        p = gen_prime(n_bits // 2)
        q = gen_prime(n_bits // 2)
        if q < p < 2 * q:
            break

    N = p * q
    euler = (p - 1) * (q - 1)

    # подбираем подходящую дешифрующую экспоненту d < (1/3) N^(1/4)
    d_max_possible_val = c_div(isqrt(isqrt(N)), 3)
    len_d_max_possible_val = d_max_possible_val.bit_length() - 1

    while True:
        d = random.getrandbits(len_d_max_possible_val)
        try:
            e = int(gmpy2.invert(d, euler))
        except ZeroDivisionError:
            continue
        if (e * d) % euler == 1:
            break

    return N, e, d, p, q
 def _step2a_start_the_searching(self):
     si = self._find_s(start_s=gmpy2.c_div(self.n, 3*self.B))
     return si
Beispiel #23
0
 def size(self, bytes=True):
     bits = number.size(self._key.n)
     if bytes:
         return gmpy2.c_div(bits, 8)
     return bits
Beispiel #24
0
print "p_max= "
print p_max.digits(10)

# calculate p_min
p_min = proot(1, dist, -(n - 1))

print "p_min= "
print p_min.digits(10)

# start finding prime
if gmpy2.is_prime(p_min):
    p = p_min
else:
    p = gmpy2.next_prime(p_min)

# loop through prime numbers from p_min to p_max
while p < p_max:
    # get remainder of div(n, p)
    rem = gmpy2.t_mod(n, p)

    if rem == 0:
        print "\nresult= "
        print "p= "
        print p.digits(10)
        print "q= "
        print gmpy2.c_div(n, p)
        sys.exit()

    p = gmpy2.next_prime(p)
Beispiel #25
0
def round3(z):
    return c_div(z, mpz(2))
Beispiel #26
0
print "p_max= "
print p_max.digits(10)

# calculate p_min
p_min = proot(1, dist, -(n - 1))

print "p_min= "
print p_min.digits(10)

# start finding prime
if gmpy2.is_prime(p_min):
	p = p_min
else:
	p = gmpy2.next_prime(p_min)

# loop through prime numbers from p_min to p_max
while p < p_max:
	# get remainder of div(n, p)
	rem = gmpy2.t_mod(n, p)

	if rem == 0:
		print "\nresult= "
		print "p= "
		print p.digits(10)
		print "q= "
		print gmpy2.c_div(n, p)
		sys.exit()

	p = gmpy2.next_prime(p)

Beispiel #27
0
        elif i == 1:
            basel = g
            left = basel
        else:
            left = gmpy2.t_mod(gmpy2.mul(left, basel), p)

        # Write result to file
        if right == left:
            ansEx = gmpy2.mul(m, j) + i
            answer = gmpy2.powmod(g, ansEx, p)

            f.write("p = " + p.digits(10))
            f.write("\ng = " + g.digits(10))
            f.write("\ny = " + y.digits(10))
            f.write("\nm = " + m.digits(10))
            f.write("\nt = " + str(j))
            f.write("\ns = " + str(i))
            f.write("\nanswer = " + ansEx.digits(10))
            f.write("\ncheck g = " + answer.digits(10))
            f.close()
            sys.exit()

        i += 1
        # pi = gmpy2.c_div((i * 100), m)
        # print "\r" + pj.digits(10) + " " + pi.digits(10) + " %",

    j += 1

    # print progress
    pj = gmpy2.c_div((j * 100), m)
    print "\r" + pj.digits(10) + " %",
Beispiel #28
0
# n = mpz('2129754913199')

# get p value
fi = open('pCurr2.txt', 'r')
p = mpz(fi.readline())
fi.close()

print p.digits(10)

# loop for prime
while p < 15000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000:
    # get remainder of div(n, p)
    rem = gmpy2.t_mod(n, p)

    if rem == 0:
        q = gmpy2.c_div(n, p)
        f = open('pResult.txt', 'a')
        f.write("p = " + p.digits(10) + "\n")
        f.write("q = " + q.digits(10) + "\n")
        f.write("n = " + n.digits(10) + "\n")
        f.close()

        fi = open('pCurr2.txt', 'w')
        fi.write(p.digits(10))
        fi.close()

        fv = open('pValue2.txt', 'a')
        fv.write(p.digits(10) + "\n")
        fv.close()
        sys.exit()
Beispiel #29
0
import gmpy2
from gmpy2 import mpz, c_div, mul, c_divmod, c_mod

n = mpz(
    837849563862443268467145186974119695264713699736869090645354954749227901572347301978135797019317859500555501198030540582269024532041297110543579716921121054608494680063992435808708593796476251796064060074170458193997424535149535571009862661106986816844991748325991752241516736019840401840150280563780565210071876568736454876944081872530701199426927496904961840225828224638335830986649773182889291953429581550269688392460126500500241969200245489815778699333733762961281550873031692933566002822719129034336264975002130651771127313980758562909726233111335221426610990708111420561543408517386750898610535272480495075060087676747037430993946235792405851007090987857400336566798760095401096997696558611588264303087788673650321049503980655866936279251406742641888332665054505305697841899685165810087938256696223326430000379461379116517951965921710056451210314300437093481577578273495492184643002539393573651797054497188546381723478952017972346925020598375000908655964982541016719356586602781209943943317644547996232516630476025321795055805235006790200867328602560320883328523659710885314500874028671969578391146701739515500370268679301080577468316159102141953941314919039404470348112690214065442074200255579004452618002777227561755664967507
)

f = open("../myI1", "r")
c = f.read()
p = mpz(c)
q = c_div(n, p)

mod = n % p
print(mod)
print(n % q)

print(p * q)
Beispiel #30
0
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",
                        "parameters": None
                    },
                    "publicKey": (pkcs1_pubkey, len(pkcs1_pubkey) * 8)
                })
            pem_name = "%s_%d_x509.pem" % (hex(my_n)[2:18], e)
import gmpy2
from gmpy2 import mpz
import random
#bit_count = 64
#rand_state = gmpy2.random_state()
c1=int(input("Enter c1:"))
c2=int(input("Enter c2:"))
e1=int(input("Enter e:"))
d1=int(input("Enter d:"))
n1=int(input("Enter n:"))
k2=gmpy2.powmod(c1,d1,n1)
jk=k2-1
k3=gmpy2.c_div(c2,gmpy2.powmod(jk,e1,n1)) 
print(int(k3))   
print(jk)  
Beispiel #32
0
# try A as ceil(sqrt(6N)) and x = sqrt(A^2 - 6N)

# first find A = ceil(sqrt(6N))
A = mul(6, N)
A = add(A, 1)
A = isqrt(A)
print 'A = ' + str(A)

# then get x = sqrt(A^2 - 6N)
x = mul(A, A)
x = sub(x, mul(6, N))
x = isqrt(x)
print 'x = ' + str(x)

# then get p = (A - x)/3 (smaller factor)
p = c_div(sub(A, x),3)
q = c_div(add(A, x),2)
N3 = mul(p, q)
print str(p) + '\n'
print str(q) + '\n'
print str(N3) + '\n'
print str(N) + '\n'
print 'three? \n'


#
# Challenge 4
c = 22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540

e = 65537
phi = mul(sub(p4, 1), sub(q4, 1))
Beispiel #33
0
# n = mpz('2129754913199')

# get p value
fi = open('pCurr2.txt', 'r')
p = mpz(fi.readline())
fi.close()

print p.digits(10)

# loop for prime
while p < 15000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000:
	# get remainder of div(n, p)
	rem = gmpy2.t_mod(n, p)

	if rem == 0:
		q = gmpy2.c_div(n, p)
		f = open('pResult.txt', 'a')
		f.write("p = " + p.digits(10) + "\n")
		f.write("q = " + q.digits(10) + "\n")
		f.write("n = " + n.digits(10) + "\n")
		f.close()

		fi = open('pCurr2.txt', 'w')
		fi.write(p.digits(10))
		fi.close()

		fv = open('pValue2.txt', 'a')
		fv.write(p.digits(10) + "\n")
		fv.close()
		sys.exit()
Beispiel #34
0
	for left in leftArray:
		if right == left:
			ansEx = gmpy2.mul(m, j) + i
			answer = gmpy2.powmod(g, ansEx, p)

			f.write("p = " + p.digits(10))
			f.write("\ng = " + g.digits(10))
			f.write("\ny = " + y.digits(10))
			f.write("\nm = " + m.digits(10))
			f.write("\nt = " + str(j))
			f.write("\ns = " + str(i))
			f.write("\nanswer = " + ansEx.digits(10))
			f.write("\ncheck g = " + answer.digits(10))
			f.close()
			sys.exit()

		i += 1

	j += 1

	# print progress
	pj = gmpy2.c_div((j * 100), m)
	print "\r" + pj.digits(10) + " %",

fi = open('iCurr.txt', 'w')
fi.write((iCurr + maxList).digits(10))
fi.close()

fv = open('iValue.txt', 'a')
fv.write((iCurr + maxList).digits(10) + "\n")
fv.close()