Ejemplo n.º 1
0
def generate_sparse_matrix(u_1, modified_secret_key, x_p):
    global global_random_state
    seed = mpz(time.time())
    global_random_state = gmpy2.random_state(seed)
    Theta_vector = [0 for _ in range(Theta)]
    for i in range(1, Theta):
        Theta_vector[i] = generate_random(kappa + 1, False, True, False)
    modified_secret_key[0] = True
    for i in range(1, Theta):
        modified_secret_key[i] = False
    count = theta - 1
    gmpy2.random_state()
    while count > 0:
        index = gmpy2.mpz_random(global_random_state, RAND_MAX) % Theta
        if not modified_secret_key[index]:
            modified_secret_key[index] = True
            count -= 1
    sum_ = zero
    temp = gmpy2.mul_2exp(one, kappa + 1)
    for i in range(1, Theta):
        if modified_secret_key[i]:
            sum_ = gmpy2.add(sum_, Theta_vector[i])
    sum_ %= temp
    u_1 = gmpy2.sub(x_p, sum_)
    if u_1 < zero:
        u_1 = gmpy2.add(temp, u_1)
    return mpz(seed), mpz(u_1)
Ejemplo n.º 2
0
def runPart3(N):
    A2 = add(isqrt(mul(24, N)), 1)
    x2 = isqrt(sub(mul(A2, A2), mul(24, N)))
    p  = div(sub(A2, x2), 6)
    q  = div(add(A2, x2), 4)
    
    return p, q
Ejemplo n.º 3
0
def factor_n1():
    '''
	Factoring challenge #1:

	The following modulus N is a products of two primes p and q where
	|p−q| < 2N^(1/4). Find the smaller of the two factors and enter it
	as a decimal integer.
	'''
    N = gmpy2.mpz(
        '179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581'
    )

    A = gmpy2.add(gmpy2.isqrt(N), one)

    x = gmpy2.isqrt(gmpy2.sub(gmpy2.mul(A, A), N))

    print 'Calculating first factors...'

    ticks = 0
    while True:
        p = gmpy2.sub(A, x)
        q = gmpy2.add(A, x)

        if gmpy2.is_prime(p) and gmpy2.is_prime(q) and gmpy2.mul(p, q) == N:
            print "p =", p, "q =", q, "ticks =", ticks
            return
        else:
            x = gmpy2.add(x, one)
            ticks += 1
            if ticks % 10000 == 0:
                print 'ticks:', ticks
Ejemplo n.º 4
0
Archivo: repos.py Proyecto: xqzy/Crypto
 def calc_near6(self):
     """ Solves the Extra Credit question Q3
     See:
     Uses only integer arithmetic to avoid issues with rounding errors
     Solution credit to Francois Degros:
     https://class.coursera.org/crypto-011/forum/thread?thread_id=517#post-2279
     :return: the prime factors of ```self.n```, p and q
     :rtype: tuple
     """
     # A = ceil(sqrt(24 N))  - the use of isqrt() won't matter, as we seek the ceil
     A = add(isqrt(mul(self.n, mpz(24))), mpz(1))
     # D = A^2 - 24 N
     D = sub(mul(A, A), mul(24, self.n))
     # E = sqrt(D)  - note D is a perfect square and we can use integer arithmetic
     E = isqrt(D)
     assert sub(mul(E, E), D) == mpz(0)
     p = div(sub(A, E), 6)
     q = div(add(A, E), 4)
     if self._check_sol(p, q):
         return p, q
     # The above is the right solution, however, there is another possible solution:
     p = div(add(A, E), 6)
     q = div(sub(A, E), 4)
     if self._check_sol(p, q):
         return p, q
     print 'Could not find a solution'
     return 0, 0
Ejemplo n.º 5
0
def generate_random(bit_size, include_negative_range, seeded, full_range):
    global global_random_state
    if not seeded or global_random_state is None:
        global_random_state = gmpy2.random_state()
    x = zero
    if full_range:
        x = gmpy2.mul_2exp(one, bit_size - 1)
    tmp = 0
    if bit_size < 33:
        tmp = gmpy2.mpz_random(global_random_state, RAND_MAX)
        temp = (1 << bit_size)
        x = gmpy2.f_mod(tmp, temp)
        if include_negative_range:
            tmp = gmpy2.mul_2exp(one, bit_size - 1)
            x = gmpy2.sub(x, tmp)
        return x
    for i in range(bit_size - 32, 0 - 1, -32):
        tmp = gmpy2.mpz_random(global_random_state, RAND_MAX)
        tmp = gmpy2.mul_2exp(tmp, i)
        x = gmpy2.add(x, tmp)
    x = gmpy2.add(x, gmpy2.mpz_random(global_random_state, RAND_MAX))
    if include_negative_range:
        tmp = gmpy2.mul_2exp(one, bit_size - 1)
        x = gmpy2.sub(x, tmp)
    return mpz(x)
Ejemplo n.º 6
0
    def addition(self, interval):
        reset_default_precision()
        res_inc_left = False
        res_inc_right = False
        if self.include_lower and interval.include_lower:
            res_inc_left = True
        if self.include_upper and interval.include_upper:
            res_inc_right = True
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundDown,
                                 precision=mpfr_proxy_precision) as ctx:
            res_left = gmpy2.add(mpfr(self.lower), mpfr(interval.lower))
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundUp,
                                 precision=mpfr_proxy_precision) as ctx:
            res_right = gmpy2.add(mpfr(self.upper), mpfr(interval.upper))

        if res_left <= res_right:
            res_right = round_number_up_to_digits(res_right, self.digits)
            res_left = round_number_down_to_digits(res_left, self.digits)
            return Interval(res_left, res_right, res_inc_left, res_inc_right,
                            self.digits)
        else:
            res_right = round_number_down_to_digits(res_right, self.digits)
            res_left = round_number_up_to_digits(res_left, self.digits)
            return Interval(res_right, res_left, res_inc_right, res_inc_left,
                            self.digits)
Ejemplo n.º 7
0
def runPart1(N):
    A = isqrt(N)
    A = add(A, 1) #couldn't find default ceil function
    x = isqrt(sub(mul(A,A), N))
    p = sub(A, x)
    q = add(A, x)

    return p, q
Ejemplo n.º 8
0
def three():
	N = mpz('720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929')
	A = mul(isqrt(mul(6,N)),2)	
	A = add(A,1)	
	x = isqrt(sub(mul(A,A),mul(24,N)))					
	p = t_div(sub(A,x),6)
	q = t_div(add(A,x),4)
	if mul(p,q) == N:
		print "3. " + str(p)
Ejemplo n.º 9
0
def one():
	N = mpz('179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581')	
	A = isqrt(N)
	A = add(A,1)
	x = isqrt(sub(mul(A,A),N))
	p = sub(A,x)
	q = add(A,x)
	if mul(p,q) == N:
		print "1. " + str(p)
	return p, q, N
Ejemplo n.º 10
0
def three():
    N = mpz(
        '720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929'
    )
    A = mul(isqrt(mul(6, N)), 2)
    A = add(A, 1)
    x = isqrt(sub(mul(A, A), mul(24, N)))
    p = t_div(sub(A, x), 6)
    q = t_div(add(A, x), 4)
    if mul(p, q) == N:
        print "3. " + str(p)
Ejemplo n.º 11
0
def prime_factor(n):
    assert n % 2 != 0

    a = add(isqrt(n), 1)  # làm tròn đến phần nguyên của A = căn(N)
    # print(a)
    x2 = add(square(a), -n)  # x^2 = a^2 - n
    # print(x2)
    p = add(a, -isqrt(x2))
    q = add(a, isqrt(x2))

    return int(p), int(q)
Ejemplo n.º 12
0
 def fun(self,coef_poly,k,t,x):
     ff = gmpy2.mpz(0)
     for j in range(k*t-k+1)[::-1]:   
        temp = gmpy2.mul(ff,x)
        ff = gmpy2.add(temp,coef_poly[j])
        if j == 1:
            break
     temp = gmpy2.mul(ff,x) #temp = at-1*xt-1+...+a1*x
     ff = gmpy2.add(temp,coef_poly[0]) #f = temp+a0
     ff = gmpy2.f_mod(ff,q)
     return ff
Ejemplo n.º 13
0
def two():
	N = mpz('648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877')
	A = isqrt(N)	
	while True:
		A = add(A,1)
		x = isqrt(sub(mul(A,A),N))
		p = sub(A,x)
		q = add(A,x)
		if mul(p,q) == N:
			print "2. " + str(p)
			break
Ejemplo n.º 14
0
def one():
    N = mpz(
        '179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581'
    )
    A = isqrt(N)
    A = add(A, 1)
    x = isqrt(sub(mul(A, A), N))
    p = sub(A, x)
    q = add(A, x)
    if mul(p, q) == N:
        print "1. " + str(p)
    return p, q, N
Ejemplo n.º 15
0
def two():
    N = mpz(
        '648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877'
    )
    A = isqrt(N)
    while True:
        A = add(A, 1)
        x = isqrt(sub(mul(A, A), N))
        p = sub(A, x)
        q = add(A, x)
        if mul(p, q) == N:
            print "2. " + str(p)
            break
Ejemplo n.º 16
0
def runPart2(N):
    A = isqrt(N)
    maxVal = add(isqrt(N), 2**20)
    p = 0
    q = 0
    
    while mul(p, q) != N and A <= maxVal:
        A = add(A, 1)
        x = isqrt(sub(mul(A,A), N))
        p = sub(A, x)
        q = add(A, x)
    
    return p, q
Ejemplo n.º 17
0
def find_factors(n):
  a = gmp.isqrt(n)
  p = 0
  q = 0

  while not check(n, p, q):
    a  = gmp.add(a, 1)
    a2 = gmp.mul(a, a)
    x  = gmp.isqrt(gmp.sub(a2, n))
    p  = gmp.mpz(gmp.sub(a, x))
    q  = gmp.mpz(gmp.add(a, x))

  return (p, q)
Ejemplo n.º 18
0
    def __next__(self):
        n = self.n

        while True:
            if n == 1:
                n = gmpy2.add(n, 1)
                continue
            elif sqrt_test(n) == False:
                if self.store:
                    self.num_list.append(n)
                self.n = gmpy2.add(n, 1)
                return n
            n = gmpy2.add(n, 1)
Ejemplo n.º 19
0
def generate_x_i(sk, length):
    tmp, q, r = 0, 0, 0
    q = gmpy2.mul_2exp(one, length - 1)
    gmpy2.random_state()
    for i in range(length - 32, 0 - 1, -32):
        tmp = gmpy2.get_random()
        tmp = gmpy2.mul_2exp(tmp, i)
        q = gmpy2.add(tmp, q)
    q = gmpy2.add(q, gmpy2.get_random())
    r = generate_random(rho, True, False, False)
    x_i = gmpy2.mul(q, sk)
    x_i = gmpy2.add(r, x_i)
    return x_i
Ejemplo n.º 20
0
def computepi():
    # N: number of decimals

    f = StringIO()
    w = xmpz(0)
    k = 1
    n1 = xmpz(4)
    n2 = xmpz(3)
    d = xmpz(1)
    f10 = xmpz(10)
    n10 = xmpz(-10)
    i = 0
    URL = request.args.get('URL', type=str)
    N = request.args.get('N', default=10, type=int)
    lenght = request.args.get('lenght', default=1, type=int)

    while True:
        # digit
        u = int(div(n1, d))
        v = int(div(n2, d))
        if u == v:
            f.write(chr(48 + u))
            i += 1
            if i % 10 == 0:
                f.write("\t:%d\n" % i)

            if i == N:
                break

            # extract
            u = mul(d, mul(n10, u))
            n1 = mul(n1, f10)
            n1 = add(n1, u)
            n2 = mul(n2, f10)
            n2 = add(n2, u)
        else:
            # produce
            k2 = k << 1
            u = mul(n1, k2 - 1)
            v = add(n2, n2)
            w = mul(n1, k - 1)
            n1 = add(u, v)
            u = mul(n2, k + 2)
            n2 = add(w, u)
            d = mul(d, k2 + 1)
            k += 1
    if lenght != 0:
        contents = urllib.request.urlopen(URL + "?N=" + str(N) + "&lenght=" +
                                          str(lenght - 1)).read()

    return (f.getvalue())
Ejemplo n.º 21
0
def find_factors_6n(n):
  n24 = gmp.mul(n, 24)
  a = gmp.isqrt(n24)
  p = 0
  q = 0

  while not check(n, p, q):
    a  = gmp.add(a, 1)
    a2 = gmp.mul(a, a)
    x  = gmp.isqrt(gmp.sub(a2, n24))
    p  = gmp.mpz(gmp.div(gmp.sub(a, x), 6))
    q  = gmp.mpz(gmp.div(gmp.add(a, x), 4))

  return (p, q)
Ejemplo n.º 22
0
def get_min_prime_root(euler_value,prime_factors,m):
    """求最小的原根"""
    a = 1
    i = 0
    while(a<m):
        for prime_factor in prime_factors:
            if gmpy2.powmod(a, gmpy2.div(euler_value, prime_factor), m) == 1:
                a = gmpy2.add(a,1)
            else:
                i = gmpy2.add(i,1)
            break
        if i == len(prime_factors):
            break
    return a
Ejemplo n.º 23
0
def FermatFactor(N):
  A = gmpy2.mpz( gmpy2.ceil( gmpy2.sqrt(N) ) )
  B2 = gmpy2.sub( gmpy2.square(A), N )

  while not gmpy2.is_square(B2): 
    A = gmpy2.add( A, gmpy2.mpz("1") )
    B2 = gmpy2.sub( gmpy2.square(A), N )
  
  B = gmpy2.sqrt(B2)
  P = gmpy2.mpz( gmpy2.sub( A, B ) )
  Q = gmpy2.mpz( gmpy2.add( A, B ) )
  if not checkFactors(P,Q,N):
    raise Exception("Bad factors generated")
  return ( P, Q )
Ejemplo n.º 24
0
 def compute_middle_point_given_interval(low, upper):
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundDown,
                              precision=mpfr_proxy_precision) as ctx:
         res_left = gmpy2.add(gmpy2.div(mpfr(upper), mpfr("2.0")),
                              gmpy2.div(mpfr(low), mpfr("2.0")))
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundUp,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = gmpy2.add(gmpy2.div(mpfr(upper), mpfr("2.0")),
                               gmpy2.div(mpfr(low), mpfr("2.0")))
     return Interval(
         round_number_down_to_digits(res_left, digits_for_range),
         round_number_up_to_digits(res_right, digits_for_range), True, True,
         digits_for_range)
Ejemplo n.º 25
0
Archivo: mqv.py Proyecto: trushev/chat
def _shared_key(a, x, x_pub, b_pub, y_pub, p):
    l2 = 2**128
    x_mod = gmpy2.t_mod_2exp(x_pub, 128)
    d = gmpy2.add(l2, x_mod)
    da = gmpy2.mul(d, a)
    xda = gmpy2.add(x, da)

    y_mod = gmpy2.t_mod_2exp(y_pub, 128)
    e = gmpy2.add(l2, y_mod)

    sa = gmpy2.powmod(b_pub, e, p)
    sa = gmpy2.mul(sa, y_pub)
    sa = gmpy2.f_mod(sa, p)
    sa = gmpy2.powmod(sa, xda, p)
    return sa
Ejemplo n.º 26
0
 def evaluate_error_at_sample(self, tree):
     """ Sample from the leaf then evaluate tree in the tree's working precision"""
     if tree.left is not None or tree.right is not None:
         if tree.left is not None:
             sample_l, lp_sample_l = self.evaluate_error_at_sample(
                 tree.left)
         if tree.right is not None:
             sample_r, lp_sample_r = self.evaluate_error_at_sample(
                 tree.right)
         if tree.root_name == "+":
             return (sample_l + sample_r), gmpy2.add(
                 mpfr(str(lp_sample_l)), mpfr(str(lp_sample_r)))
         elif tree.root_name == "-":
             return (sample_l - sample_r), gmpy2.sub(
                 mpfr(str(lp_sample_l)), mpfr(str(lp_sample_r)))
         elif tree.root_name == "*":
             return (sample_l * sample_r), gmpy2.mul(
                 mpfr(str(lp_sample_l)), mpfr(str(lp_sample_r)))
         elif tree.root_name == "/":
             return (sample_l / sample_r), gmpy2.div(
                 mpfr(str(lp_sample_l)), mpfr(str(lp_sample_r)))
         elif tree.root_name == "exp":
             return np.exp(sample_l), gmpy2.exp(mpfr(str(sample_l)))
         elif tree.root_name == "sin":
             return np.sin(sample_l), gmpy2.sin(mpfr(str(sample_l)))
         elif tree.root_name == "cos":
             return np.cos(sample_l), gmpy2.cos(mpfr(str(sample_l)))
         elif tree.root_name == "abs":
             return np.abs(sample_l), abs(mpfr(str(sample_l)))
         else:
             print("Operation not supported!")
             exit(-1)
     else:
         sample = tree.root_value[0].getSampleSet(n=1)[0]
         return sample, mpfr(str(sample))
Ejemplo n.º 27
0
    def generate_private_key(self, vec):
        assert len(vec) <= self.eta

        sk = gp.mpz(0)
        for i in range(len(vec)):
            sk = gp.add(sk, gp.mul(self.msk[i], vec[i]))
        return {'bound': len(vec), 'sk': gp.digits(sk)}
Ejemplo n.º 28
0
def verify(A, x, N):
    p = gmpy2.sub(A, x)
    q = gmpy2.add(A, x)
    if gmpy2.mul(p, q) == N:
        return [True, p, q]
    else:
        return [False, p, q]
Ejemplo n.º 29
0
def chinrest(aas, ns):
    count = len(aas)
    m = 1
    ms = [1] * count
    ees = [mpz(0)] * count

    # product of all ns
    for i in range(0, count):
        m = gmpy2.mul(m, ns[i])

# products of all but one ns
    for i in range(0, count):
        ms[i] = gmpy2.div(m, ns[i])

# extended euclid to get the factors
    for i in range(0, count):
        ggtn, r, s = gmpy2.gcdext(mpz(ns[i]), mpz(ms[i]))
        ees[i] = gmpy2.mul(s, ms[i])

# calculating x
    x = 0
    for i in range(0, count):
        x = gmpy2.add(x, gmpy2.mul(aas[i], ees[i]))


# making x positive. just in case
    x = gmpy2.t_mod(mpz(x), mpz(m))
    while x < 0:
        x = gmpy2.t_mod(mpz(x + m), mpz(m))

    return m, x
Ejemplo n.º 30
0
def verify(A,x,N):
    p = gmpy2.sub(A,x)
    q = gmpy2.add(A,x)
    if gmpy2.mul(p, q) == N:
        return [True,p,q]
    else:
        return [False,p,q]
Ejemplo n.º 31
0
    def generate_keys(n_bits=1024):
        """
        Generates keys necessary to Pailler's Cryptossystem 
        
        Parameters:
            Kwargs:
                n_bits: Size of the key, in bits (default=1024)
        
        Returns:
            Tuple: Tuple containing two tuples:
                t0: Tuple containing the public key (n,g)
                t1: Tuple containing the private key (lambda,mu)
                   
        """

        one = gmpy2.mpz(1)
        p = new_prime(n_bits=n_bits)
        q = new_prime(n_bits=n_bits)

        # public key
        n = gmpy2.mul(p, q)
        g = gmpy2.add(n, one)

        #private key
        lbd = gmpy2.mul(gmpy2.sub(p, one), gmpy2.sub(q, one))
        mu = gmpy2.powmod(lbd, -1, n)

        return ((n, g), (lbd, mu))
Ejemplo n.º 32
0
def Q1Q4():
    N = mpz('17976931348623159077293051907890247336179769789423065727343008115\
    77326758055056206869853794492129829595855013875371640157101398586\
    47833778606925583497541085196591615128057575940752635007475935288\
    71082364994994077189561705436114947486504671101510156394068052754\
    0071584560878577663743040086340742855278549092581')

    A = isqrt(N) + 1
    x = isqrt(sub(mul(A, A), N))

    p = sub(A, x)
    q = add(A, x)

    print("Q1:")
    print(p)

    fiN = mul(sub(p, 1), sub(q, 1))
    e = mpz(65537)
    d = gmpy2.invert(e, fiN)
    ct = mpz('22096451867410381776306561134883418017410069787892831071731839143\
            67613560012053800428232965047350942434394621975151225646583996794\
            28894607645420405815647489880137348641204523252293201764879166664\
            02997509188729971690526083222067771600019329260870009579993724077\
            458967773697817571267229951148662959627934791540')
    pt = gmpy2.powmod(ct, d, N)
    ptstr = pt.digits(16)
    pos = ptstr.find('00')
    payload = ptstr[pos + 2:]
    
    print("Q4:")
    print(binascii.unhexlify(payload))
Ejemplo n.º 33
0
def dlog(pgh):

	p = pgh[0]
	g = pgh[1]
	h = pgh[2]

	B = gmpy2.powmod(2,20,mpz(p))
	B_low = 0
	#B_low = gmpy2.powmod(2,18,mpz(p))
	print "B: " + repr(B)

	# build the hash
	hash_table = {}
	for i in range(B_low,B):
		left = gmpy2.divm(mpz(h),gmpy2.powmod(mpz(g),i, mpz(p)),mpz(p))
		try:
			hash_table[left]
			print "collision at " + i
		except KeyError:
			hash_table[left] = i
			continue

	print "Hash table built"
	#print "keys: " + repr(hash_table.keys())

	counter = mpz(0)
	# meet in the middle
	x0 = mpz(0)
	x1 = mpz(0)
	for i in range(B_low,B):
		counter = gmpy2.add(counter,mpz(1))
		right = gmpy2.powmod(gmpy2.powmod(mpz(g),mpz(B),mpz(p)),i,mpz(p))
		try:
			h_entry = hash_table[right] 
			print 'found x0 and x1...'
			x0 = i
			x1 = h_entry
			print 'x0=' + repr(x0)
			print 'x1=' + repr(x1)
			
			break
		except KeyError:
			continue

	print "counter: " + repr(counter)
	x = gmpy2.t_mod(gmpy2.add(gmpy2.mul(x0,B),x1), mpz(p))
	return x
Ejemplo n.º 34
0
def generate_x(x, sk):
    gmpy2.random_state()
    q, r = 0, 0
    q = generate_random(gamma - eta, False, False, False)
    r = generate_random(rho, True, False, False)
    x = gmpy2.mul(q, sk)
    x = gmpy2.add(r, x)
    return mpz(x)
Ejemplo n.º 35
0
def is_prime(r):
    for k in range(0,10000000):
        p = gmpy2.add(r, k)
        a = gmpy2.powmod(2, p-1, p)

        if (a == 1): 
            print "k = %i \nprime = %i\n" % (k, p)
            return
Ejemplo n.º 36
0
Archivo: repos.py Proyecto: xqzy/Crypto
 def solve_quadratic(a, b, c):
     """ Solves the quadratic equation ```a x2 + b x + c = 0```
     :return: the GMP result of solving the quadratic equation usign multi-precision numbers
     """
     bb = sqrt(sub(mul(b, b), mul(mpz(4), mul(a, c))))
     x1 = gmpy2.div(sub(-b, bb), mul(mpz(2), a))
     x2 = gmpy2.div(add(-b, bb), mul(mpz(2), a))
     return x1, x2
Ejemplo n.º 37
0
def is_prime(r):
    for k in range(0, 10000000):
        p = gmpy2.add(r, k)
        a = gmpy2.powmod(2, p - 1, p)

        if (a == 1):
            print "k = %i \nprime = %i\n" % (k, p)
            return
Ejemplo n.º 38
0
def get_h_pwd(coordinates):
    x = map(lambda x: x[0], coordinates)  # extract the x and y coordinates
    y = map(lambda x: x[1], coordinates)
    h_pwd_ = mpz()
    for i in xrange(config.max_features):
        h_pwd_ = gmpy2.add(h_pwd_, gmpy2.t_mod(gmpy2.mul(y[i], get_lambda_i(x, i)), config.q))
    h_pwd_ = gmpy2.t_mod(h_pwd_, config.q)
    return h_pwd_
Ejemplo n.º 39
0
def find_x(h, g, p, B):
    table = build_table(h, g, p, B)
    x0, x1 = lookup(table, g, p, B)
    # assert x0 != None and x1 != None
    Bx0 = mul(x0, B)
    x = add(Bx0, x1)
    # print(x0, x1)
    return x
Ejemplo n.º 40
0
 def __iadd__(self, other):
     if type(other
             ) is GaloisFieldNumber and self.exponent == other.exponent:
         self.encoding = gmpy2.mod(gmpy2.add(self.encoding, other.encoding),
                                   self.gfp.p)
         return self
     else:
         return self + other
Ejemplo n.º 41
0
def computepi():
    # N: number of decimals

    f = StringIO()
    w = xmpz(0)
    k = 1
    n1 = xmpz(4)
    n2 = xmpz(3)
    d = xmpz(1)
    f10 = xmpz(10)
    n10 = xmpz(-10)
    i = 0
    N = request.args.get('N', default=10, type=int)

    while True:
        # digit
        u = int(div(n1, d))
        v = int(div(n2, d))
        if u == v:
            f.write(chr(48 + u))
            i += 1
            if i % 10 == 0:
                f.write("\t:%d\n" % i)

            if i == N:
                break

            # extract
            u = mul(d, mul(n10, u))
            n1 = mul(n1, f10)
            n1 = add(n1, u)
            n2 = mul(n2, f10)
            n2 = add(n2, u)
        else:
            # produce
            k2 = k << 1
            u = mul(n1, k2 - 1)
            v = add(n2, n2)
            w = mul(n1, k - 1)
            n1 = add(u, v)
            u = mul(n2, k + 2)
            n2 = add(w, u)
            d = mul(d, k2 + 1)
            k += 1
    return (f.getvalue())
Ejemplo n.º 42
0
Archivo: repos.py Proyecto: xqzy/Crypto
 def calc_brute_force(self):
     a = ceil(sqrt(self.n))
     for n in xrange(1, 2 ** 20):
         p, q = self._calc_factors(add(a, n))
         if self._check_sol(p, q):
             return p, q
         #self.log.print_progress(n)
     else:
         raise ValueError("Cannot factor {}".format(self.n))
Ejemplo n.º 43
0
 def calculate_shared_secret(self):
     val = powmod(self.generator, self.get_identity_hash(), self.modulus)
     val2 = mul(self.get_multiplier(), val)
     val3 = sub(self.get_server_public_value(), val2)
     val4 = mul(self.get_scrambler(), self.get_identity_hash())
     val5 = add(self.get_private_value(), val4)
     val6 = t_mod(val3, self.modulus)
     val7 = t_mod(val5, self.modulus)
     self.shared_secret = powmod(val6, val7, self.modulus)
Ejemplo n.º 44
0
 def add_all_coefficients_upper_abs(self):
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundAwayZero,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = mpfr("0.0")
         for coeff in self.coefficients:
             res_right = gmpy2.add(
                 res_right, abs(mpfr(self.coefficients[coeff].upper)))
         # now the number is positive so we can round up
         return round_number_up_to_digits(res_right, digits_for_range)
 def get_random_value(self, start_pow, p=None):
     """ Sample a random value based on self.rng of p bits between [0,2^(start_pow+1)). """
     if p == None:
         p = self.context.precision
     s = mpfr(0)
     nextbit = gmpy2.exp2(start_pow)
     for i in range(1, p):
         s = gmpy2.add(s, gmpy2.mul(nextbit, mpfr(self.rng())))
         nextbit = gmpy2.exp2(start_pow - i)
     return s
Ejemplo n.º 46
0
def main():
    # predefine these, we will stop overwriting them when ready to run the big numbers
    p=mpz('13407807929942597099574024998205846127'
         '47936582059239337772356144372176403007'
         '35469768018742981669034276900318581848'
         '6050853753882811946569946433649006084171'
         )
    g=mpz('117178298803662070095161175963353670885'
         '580849999989522055999794590639294997365'
         '837466705721764714603129285948296754282'
         '79466566527115212748467589894601965568'
        )
    y=mpz('323947510405045044356526437872806578864'
         '909752095244952783479245297198197614329'
         '255807385693795855318053287892800149470'
         '6097394108577585732452307673444020333'
         )

    log.info("Starting Discrete Log Calculation")
    log.info("p: %i", p)
    log.info("g: %i", g)
    log.info("y: %i", y)

    m = gmpy2.ceil(gmpy2.sqrt(p))
    log.info("m: %i", m)

    # custom range since builtin has a size limit
    long_range = lambda start, stop: iter(itertools.count(start).next, stop)
    chunk_size = 100000
    
    if m < 100000:
        chunk_size = m
    
    stop_at = chunk_size
    start = 0

    while True:
        chunk = {}
        log.info("Starting chunk from %i to %i", start, stop_at)
        for i in xrange(start, stop_at):
            chunk[gmpy2.powmod(g,i,p)] = i
        for t in long_range(0,m):
            expone = mpz(gmpy2.mul(-m,t))
            g_term = gmpy2.powmod(g, expone, p)
            res = gmpy2.f_mod(gmpy2.mul(y, g_term), p)
            if res in chunk:
                s = chunk[res]
                dc = gmpy2.f_mod(mpz(gmpy2.add(s, gmpy2.mul(m,t))), p)
                log.info("DC LOG FOUND")
                log.info("dc: %i", dc)
                return
        log.info("Completed chunk run: %i to %i  no DC yet :(", start, stop_at)
        start = stop_at
        stop_at += chunk_size
Ejemplo n.º 47
0
 def compute(self):
     self.build_table(end=self.B)
     rhs = self.g_B
     for x0 in xrange(1, self.B):
         x1 = self.lookup_table.get(rhs, None)
         if x1:
             res = gmpy2.f_mod(gmpy2.add(gmpy2.mul(x0, self.B), x1), self.p)
             return res
         if x0 and (x0 % self.CHECKPOINT) == 0:
             self.log.print_progress(x0)
         rhs = gmpy2.f_mod(gmpy2.mul(rhs, self.g_B), self.p)
Ejemplo n.º 48
0
def factorize(N,ran):
    for i in ran:
        A = gmpy2.add(gmpy2.isqrt(N),i)
        Asq = gmpy2.mul(A,A)
        diff = gmpy2.sub(Asq, N)
        x = gmpy2.isqrt_rem(diff)[0]
        [correct,p,q] = verify(A,x,N)
        if(correct):
            print p
            return [p,q]
    print "Not Found"
Ejemplo n.º 49
0
def factorize(N, ran):
    for i in ran:
        A = gmpy2.add(gmpy2.isqrt(N), i)
        Asq = gmpy2.mul(A, A)
        diff = gmpy2.sub(Asq, N)
        x = gmpy2.isqrt_rem(diff)[0]
        [correct, p, q] = verify(A, x, N)
        if (correct):
            print p
            return [p, q]
    print "Not Found"
Ejemplo n.º 50
0
def computeN2Factors():
    p = 0
    q = 0
    A = computeA(N2)

    while not confirmed(N2, p, q):
        A2 = pow(A, 2)
        assert A2 > N2
        x = gmpy2.sqrt(gmpy2.sub(A2, N2))
        p = gmpy2.sub(A, x)
        q = gmpy2.add(A, x)
        A += 1
Ejemplo n.º 51
0
 def findDiscreteLog(self):
     x = -1
     element_powB = gmpy2.powmod(mpz(self.element), mpz(self.B), mpz(self.prime))
     for x0 in range (0, self.B + 1):
         right_x0 = gmpy2.powmod(element_powB, x0, mpz(self.prime))
         if right_x0 in self.h_by_gx_hash:
              print("x0: %d" % (x0))
              x1 = self.h_by_gx_hash[right_x0]
              print("x1: %d" % (x1))
              x = gmpy2.t_mod(gmpy2.add(gmpy2.mul(x0, self.B), x1), mpz(self.prime))
              print("x: %d" % (x))
              return str(x)
     return x
def isqrt(x): 
    ''' 
    Writing your own square root function
    ''' 
    if x < 0: raise ValueError('square root not defined for negative numbers') 
    n = mpz(x) 
    if n == 0: return 0 
    a, b = t_divmod(n.bit_length(), mpz(2)) 
    x = 2**(a + b) 
    while True: 
        y = div(add(x, div(n, x)), 2 )
        if y >= x: return x 
        x = y 
Ejemplo n.º 53
0
def q3():
    N = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929

    rt = gmpy2.sqrt(gmpy2.mul(N, 6))
    A = gmpy2.ceil(rt)

    A2 = pow(A, 2)
    assert A2 > N

    x = gmpy2.sqrt(gmpy2.sub(A2, N))
    x = gmpy2.mul(x, 3/2)
    p = gmpy2.sub(A, x)
    q = gmpy2.add(A, x)
    gotcha(N, p, q)
Ejemplo n.º 54
0
def generate(pwd, stat):
    config.generate_r()
    pwd = mpz(crypt.get_bit_str_from_byte(pwd), base=2)
    global table
    table = []  # clear the table
    for i in xrange(config.max_features):
        x_0 = crypt.p(mpz((i + 1) << 1), config.r)  # calculate x0, x1 and y0, y1
        x_1 = crypt.p(mpz(((i + 1) << 1) + 1), config.r)
        y_0 = gmpy2.add(poly.calculate(x_0), crypt.g(mpz((i + 1) << 1), config.r ^ pwd))  # use r xor pwd as the key
        y_1 = gmpy2.add(poly.calculate(x_1), crypt.g(mpz(((i + 1) << 1) + 1), config.r ^ pwd))
        if reader.if_init():
            table.append((y_0, y_1))  # if in initialization phase, add correct value
        else:
            if stat[i][0] is None:
                table.append((y_0, y_1))  # if no statistic information is derived
            elif (stat[i][1] + stat[i][0] * config.k) < config.ti:  # if fast
                rand_value = gmpy2.t_mod(config.generate_rand(), config.q)
                table.append((y_0, rand_value))
            elif (stat[i][1] - stat[i][0] * config.k) > config.ti:  # if slow
                rand_value = gmpy2.t_mod(config.generate_rand(), config.q)
                table.append((rand_value, y_1))
            else:
                table.append((y_0, y_1))
Ejemplo n.º 55
0
def q1():
    N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581

    rt = gmpy2.sqrt(N)
    A = gmpy2.ceil(rt)
    A2 = pow(A, 2)

    assert A2 > N

    x = gmpy2.sqrt(gmpy2.sub(A2, N))

    p = gmpy2.sub(A, x)
    q = gmpy2.add(A, x)
    gotcha(N, p, q)
Ejemplo n.º 56
0
def bruteSmall(N):
  zero = g.mpz(0)
  two = g.mpz(2)
  if g.f_mod(N, two) == zero:
    return two, g.mpz(g.div(N, two))

  i = g.mpz(3)
  while True:
    if g.f_mod(N, i) == zero:
      p = g.mpz(i)
      q = g.mpz( g.div(N,i) )
      if checkFactors(p,q,N) :
        return p,q
    i = g.add(i, two)
Ejemplo n.º 57
0
def pi_calc():
    global calcs, y, u, q, r, t, j, calc_uy, startTime
    digitstring = ''
    dpm = 0
    strPi = ''
    loop = 1
    elapsed = 0
    elapsedStart = time.time()
    while loop:
        digitCalcTime = time.time()
        j3 = mul(3, j)
        u, y = mpz(3 * (j3 + 1) * (j3 + 2)), mpz(div((add(mul(q, (mul(27, j)) - 12), mul(5, r))), mul(5, t)))
        strPi = str(y)
        digitstring += strPi
        q, r, t, j = mpz(mul((20 * j ** 2 - mul(10, j)), q)), \
                     mpz(mul(mul(10, u), (q * (mul(5, j) - 2) + r - mul(y, t)))), \
                     mpz(mul(t, u)), add(j, 1)
        # dpm = digits per minute
        now = time.time()
        elapsed = now - elapsedStart
        # if the elapsed calculation time exceeds .5 seconds break the loop and return the digits calculated
        if elapsed >= 1:
            break
        elif (j - 2) % 1000 == 0:  # break also every 1000nth digit to report stats
            break
    dps = (1.0 / elapsed) * len(digitstring)
    info = {
        "digits": digitstring,
        "digitcount": int(j) - 2,
        "dpm": round(dps * 60),
        "dps": round(dps, 2)
    }
    if (j - 2) % 1000 == 0:
        info['mark'] = {"digitmark": (int(str(j)) - 2),
                        "runtime": time.time() - startTime}
    return info
Ejemplo n.º 58
0
    def Run_MFun(self, itermax, Z_0):
        """ Expects gmpy2.mpc type for Z_0. """

        if not gmpy2.get_context().precision == self.prec:
            gmpy2.get_context().precision = self.prec

        Z = Z_0

        while self.iters < itermax:
            Z = add( gmpy2.mul(Z,Z), self.C )
            if norm(Z) > 4.0:
                break
            self.iters += 1
            
        if self.iters == itermax:
            self.inmset = True
Ejemplo n.º 59
0
def Q3():
    N = mpz('72006226374735042527956443552558373833808445147399984182665305798191\
    63556901883377904234086641876639384851752649940178970835240791356868\
    77441155132015188279331812309091996246361896836573643119174094961348\
    52463970788523879939683923036467667022162701835329944324119217381272\
    9276147530748597302192751375739387929')

    A = isqrt(mul(6, N)) + 1
    # (3 * p + 2 * q) / 2 is not an integer. or, A - 0.5 = (3p + 2q) / 2
    # so, x = sqrt((A-0.5)^2 - 6N) = sqrt(A^2 - A + 0.25 - 6N). the 0.25 term can be thrown away.
    x = isqrt(sub(sub(mul(A, A), A), mul(6, N)))
    p = div(sub(A, x), 3)
    q = div(add(A, x), 2)

    if mul(p, q) == N:
        print("Q3:")
        print(p)
Ejemplo n.º 60
0
def Q2():
    N = mpz('6484558428080716696628242653467722787263437207069762630604390703787\
    9730861808111646271401527606141756919558732184025452065542490671989\
    2428844841839353281972988531310511738648965962582821502504990264452\
    1008852816733037111422964210278402893076574586452336833570778346897\
    15838646088239640236866252211790085787877')

    for d in range(1, 1<<20):
        A = isqrt(N) + d
        x = isqrt(sub(mul(A, A), N))

        p = sub(A, x)
        q = add(A, x)

        if mul(p, q) == N:
            print("Q2:")
            print(p)
            break