Ejemplo n.º 1
0
def pohlig_hellman(g, h, M, factors):
    M1 = M - 1
    xs = []
    for f in factors:
        pf = f
        pe = factors[f]

        subgroup_exponent = gmpy2.div(M1, gmpy2.powmod(pf, pe, M))
        gi = gmpy2.powmod(g, subgroup_exponent, M)
        hi = gmpy2.powmod(h, subgroup_exponent, M)

        xi = log_prime_power(gi, hi, pf, pe, M)
        xs.append(xi)
    crt_coeffs = []

    for f in factors:
        pf = f
        pe = factors[f]

        mi = pf**pe

        bi = gmpy2.div(M, mi)
        bi_inv = gmpy2.invert(bi, mi)
        crt_coeffs.append(gmpy2.mul(bi, bi_inv))
    x = 0
    for i in range(len(crt_coeffs)):
        x = gmpy2.t_mod(x + gmpy2.t_mod(xs[i] * crt_coeffs[i], M1), M1)
    return x
Ejemplo n.º 2
0
def ch3_factor(N):
    """ Valid when |3p - 2q| < N^(1/4)
    """

    A = ceil_sqrt(6 * N)

    # let M = (3p+2q)/2
    # M is not an integer since 3p + 2q is odd
    # So there is some integer A = M + 0.5 and some integer i such that
    # 3p = M + i - 0.5 = A + i - 1
    # and
    # 2q = M - i + 0.5 = A - i
    #
    # N = pq = (A-i)(A+i-1)/6 = (A^2 - i^2 - A + i)/6
    # So 6N = A^2 - i^2 - A + i
    # i^2 - i = A^2 - A - 6N

    # Solve using the quadratic equation!
    a = mpz(1)
    b = mpz(-1)
    c = -(A**2 - A - 6 * N)

    det = b**2 - 4 * a * c

    roots = (div(-b + isqrt(b**2 - 4 * a * c),
                 2 * a), div(-b - isqrt(b**2 - 4 * a * c), 2 * a))

    for i in roots:
        if i >= 0:
            f = check_ch3(i, A, N)
            if f:
                return f

    # We should have found the root
    assert (False)
Ejemplo n.º 3
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.º 4
0
def main(argv):
    lines      = files.read_lines(argv[0])
    N_1        = mpz(lines[0])
    N_2        = mpz(lines[1])
    N_3        = mpz(lines[2])

    lines      = files.read_lines(argv[1])
    C          = mpz(lines[0])
    E          = int(lines[1])

    p1, q1, i1 = number.factorize(N_1, 1)
    p2, q2, i2 = number.factorize(N_2, 1048576)
    p3, q3, i3 = number.factorize(mul(N_3, 24), 1)

    print
    print 'Factorization Demo'
    print
    print '       1st:'
    print 'Iterations: ', i1
    print '         p: ', p1
    print '         q: ', q1
    print
    print '       2nd:'
    print 'Iterations: ', i2
    print '         p: ', p2
    print '         q: ', q2
    print
    print '       3rd:'
    print 'Iterations: ', i3
    print '         p: ', div(p3, 6)
    print '         q: ', div(q3, 4)
    print
    print
    print ' Plaintext: ', encdec.rsa_decrypt(C, E, p1, q1, N_1)
    print
Ejemplo n.º 5
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.º 6
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.º 7
0
def check_ch3(i, A, N):
    p, q = (div(A + i - 1, 3), div(A - i, 2))
    if check_factors(p, q, N):
        return p, q

    p, q = (div(A - i, 3), div(A + i - 1, 2))
    if check_factors(p, q, N):
        return p, q

    return None
Ejemplo n.º 8
0
def check_ch3(i,A,N):
    p,q = (div(A + i - 1,3), div(A - i,2))
    if check_factors(p,q,N):
        return p,q

    p,q = (div(A - i,3), div(A + i - 1,2))
    if check_factors(p,q,N):
        return p,q

    return None
Ejemplo n.º 9
0
def challenge3():
    """
    Valid when |3p - 2q| < N^(1/4)

    Solving
    >>> 6N = A^2 - i^2 - A + i
    

    >>> [ax^2 + bx + c              = 0]
    >>>  1i^2 - 1i - (A^2 - A - 6N) = 0

    Therefore:

        a = 1
        b = -1
        c = (A^2 - A - 6N)
    """

    print("> Challenge 3")
    N = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929
    A = gmpy2.ceil(gmpy2.sqrt(6*N))
    
    a = gmpy2.mpz(1)
    b = gmpy2.mpz(-1)
    c = gmpy2.mpz(-(A**2 - A - 6*N))

    # Solving using quadratic formula
    # 
    #   x = (-b (+/-) b^2 - 4ac) / 2a
    #
    # b^2 - 4ac
    det = gmpy2.isqrt(b**2 - 4*a*c)

    plus = gmpy2.div(-b + det, 2*a)
    minus = gmpy2.div(-b - det, 2*a)

    answers = [plus, minus]

    for i in answers:

        # check for correct answer
        p = gmpy2.mpz(gmpy2.div(A + i - 1, 3))
        q = gmpy2.mpz(gmpy2.div(A - i, 2))

        # values found
        if p*q == N:
            printSmallest(p, q)

            return


    raise(Exception("[Challenge 3] > Could not find p or q"))
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
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.º 12
0
def computeN3Factors():
    A = gmpy2.ceil(gmpy2.mul(2, gmpy2.sqrt(gmpy2.mul(6, N3))))
    X = gmpy2.ceil(
        gmpy2.sqrt(
            gmpy2.sub(
                pow(A, 2),
                gmpy2.mul(24, N3)
            )
        )
    )
    p = gmpy2.ceil(gmpy2.div(gmpy2.sub(A, X), 6)) # Only round one.
    q = gmpy2.div(N3, p)
    confirmed(N3, p, q)
Ejemplo n.º 13
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.º 14
0
 def Dec(self, PP, sk, c):
     p = self.PP['p']
     a = c['a']
     b = c['b']
     m = 0
     if b < 0:
         b_mod = -b
         m_mod = gmpy2.div(a, b_mod**sk) % p
         m = -m_mod
     else:
         b_mod = b
         m_mod = gmpy2.div(a, b_mod**sk) % p
         m = m_mod
     return m
Ejemplo n.º 15
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.º 16
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.º 17
0
def attack3(N):
    """
    |3p-2q|<N^(1/4)
    """
    N *= 4
    A, r = gmpy2.isqrt_rem(6 * N)
    if (r > 0):
        A += 1
    x, r = gmpy2.isqrt_rem(A * A - 6 * N)
    if (r > 0):
        x += 1

    if (N % div(A - x, 6) == 0 and N % div(A + x, 4) == 0):
        print("Factors are ", div(A - x, 6), div(A + x, 4))
Ejemplo n.º 18
0
def regenerate_key(bits,x,x_i,L,leave):
    """ Regenerate the key r when some peer join or leave the team. All the variables' name are the same as those used in the paper.
        Args:
            bits: int, the number of bits of p, which can be set to be larger than the length of r.
            x: list, x_i which has been distributed members.
            x_i: int, the x_i of a member who wants to join or leave the team.
            L: int, the value of product of x_is before the member join or leave.
            leave: bool. True if the x_i is leaving the team. False if the x_i is join the team.
    """  

    p=generate_large_prime(bits)
    (m,q)=generate_m(p)
    
    delta= generate_large_prime(len(bin(min(x)))-2)
    k=delta-p
    
    a=generate_large_prime(bits)
    g=gmpy2.powmod(a,q,m)
    
        
    r=gmpy2.powmod(g,k,m)
    
    if leave :
       L=gmpy2.div(L,x_i)
    else:
       L=gmpy2.mul(L,x_i)
       
    u=gmpy2.invert(delta,L)
    
    while get_key(g,m,u,x[0])!=r:
        p=generate_large_prime(bits)
        (m,q)=generate_m(p)
        
        delta= generate_large_prime(len(bin(min(x)))-2)
        k=delta-p
        
        a=generate_large_prime(bits)
        g=gmpy2.powmod(a,q,m)
            
        r=gmpy2.powmod(g,k,m)
        
        if leave :
           L=gmpy2.div(L,x_i)
        else:
           L=gmpy2.mul(L,x_i)
           
        u=gmpy2.invert(delta,L)
        
        
    return (g,m,u,L,r)
Ejemplo n.º 19
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.º 20
0
def prime_factor(n):
    assert n % 2 != 0

    a = isqrt(24 * n) + 1  # làm tròn đến phần nguyên của A = căn(6N)
    # print(a)
    x2 = add(square(a), -24 * n)  # x^2 = a^2 - n
    # print(x2)
    '''
    while not is_square(x2):
        a += 1
        x2 = square(a) - 24*n
    '''
    p = div(a - isqrt(x2), 6)
    q = div(a + isqrt(x2), 4)

    return int(p), int(q)
Ejemplo n.º 21
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.º 22
0
def legendre_symbol():
    p = 101524035174539890485408575671085261788758965189060164484385690801466167356667036677932998889725476582421738788500738738503134356158197247473850273565349249573867251280253564698939768700489401960767007716413932851838937641880157263936985954881657889497583485535527613578457628399173971810541670838543309159139
    ints = [
        25081841204695904475894082974192007718642931811040324543182130088804239047149283334700530600468528298920930150221871666297194395061462592781551275161695411167049544771049769000895119729307495913024360169904315078028798025169985966732789207320203861858234048872508633514498384390497048416012928086480326832803,
        45471765180330439060504647480621449634904192839383897212809808339619841633826534856109999027962620381874878086991125854247108359699799913776917227058286090426484548349388138935504299609200377899052716663351188664096302672712078508601311725863678223874157861163196340391008634419348573975841578359355931590555,
        17364140182001694956465593533200623738590196990236340894554145562517924989208719245429557645254953527658049246737589538280332010533027062477684237933221198639948938784244510469138826808187365678322547992099715229218615475923754896960363138890331502811292427146595752813297603265829581292183917027983351121325,
        14388109104985808487337749876058284426747816961971581447380608277949200244660381570568531129775053684256071819837294436069133592772543582735985855506250660938574234958754211349215293281645205354069970790155237033436065434572020652955666855773232074749487007626050323967496732359278657193580493324467258802863,
        4379499308310772821004090447650785095356643590411706358119239166662089428685562719233435615196994728767593223519226235062647670077854687031681041462632566890129595506430188602238753450337691441293042716909901692570971955078924699306873191983953501093343423248482960643055943413031768521782634679536276233318,
        85256449776780591202928235662805033201684571648990042997557084658000067050672130152734911919581661523957075992761662315262685030115255938352540032297113615687815976039390537716707854569980516690246592112936796917504034711418465442893323439490171095447109457355598873230115172636184525449905022174536414781771,
        50576597458517451578431293746926099486388286246142012476814190030935689430726042810458344828563913001012415702876199708216875020997112089693759638454900092580746638631062117961876611545851157613835724635005253792316142379239047654392970415343694657580353333217547079551304961116837545648785312490665576832987,
        96868738830341112368094632337476840272563704408573054404213766500407517251810212494515862176356916912627172280446141202661640191237336568731069327906100896178776245311689857997012187599140875912026589672629935267844696976980890380730867520071059572350667913710344648377601017758188404474812654737363275994871,
        4881261656846638800623549662943393234361061827128610120046315649707078244180313661063004390750821317096754282796876479695558644108492317407662131441224257537276274962372021273583478509416358764706098471849536036184924640593888902859441388472856822541452041181244337124767666161645827145408781917658423571721,
        18237936726367556664171427575475596460727369368246286138804284742124256700367133250078608537129877968287885457417957868580553371999414227484737603688992620953200143688061024092623556471053006464123205133894607923801371986027458274343737860395496260538663183193877539815179246700525865152165600985105257601565
    ]
    x = -1
    for i in ints:
        if euler_criterion(
                i, p) == 1:  # 1 means that the number is a quadratic residue
            x = i  # this is the quadratic residue

    # a^2 = x mod p
    # b^p cong b mod p
    gmpy2.get_context().precision = 10000
    # temp = gmpy2.div(p+1, 4)
    # print(temp)
    a = pow(x, int(gmpy2.div(p + 1, 4)), p)
    # a = (pow(x, p/2, p))
    # print(int(a) == a)
    print(a)
Ejemplo n.º 23
0
def diophantine(a, b, c):
    q, r = gmpy2.f_divmod(a, b)

    if (r == 0):
        print "remainder = ", gmpy2.div(c, b)
        return ([0, gmpy2.div(c, b)])

    else:
        sol = diophantine(b, r, c)
        x = sol[1]
        y = sol[0]

        print "x = ", x
        print "y = ", y

        return ([x, gmpy2.sub(y, gmpy2.mul(x, q))])
Ejemplo n.º 24
0
def diophantine(a, b, c):
    q,r = gmpy2.f_divmod(a, b)

    if (r == 0):
        print "remainder = ", gmpy2.div(c, b)
        return([0, gmpy2.div(c, b)])

    else:
        sol = diophantine(b, r, c)
        x = sol[1]
        y = sol[0]

        print "x = ", x
        print "y = ", y

        return ([x, gmpy2.sub(y, gmpy2.mul(x, q))])
Ejemplo n.º 25
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.º 26
0
 def compute_uncertainty_given_interval(low, upper):
     coefficients = {}
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundDown,
                              precision=mpfr_proxy_precision) as ctx:
         res_left = gmpy2.sub(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.sub(gmpy2.div(mpfr(upper), mpfr("2.0")),
                               gmpy2.div(mpfr(low), mpfr("2.0")))
     coefficients[AffineManager.get_new_error_index()]=\
         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)
     return coefficients
Ejemplo n.º 27
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.º 28
0
def chinese_remainder(n, a):
    sum = 0
    prod = reduce(gmpy2.mul, n)

    for n_i, a_i in zip(n, a):
        p = gmpy2.div(prod, n_i)
        sum += gmpy2.mul(gmpy2.mul(a_i, mul_inv(p, n_i)), p)
    return sum % prod
Ejemplo n.º 29
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())
def get_smoothness(_start, delta, list_primes, pos, output):
    print("start process " + str(pos))

    segment = math.ceil(delta / 10)
    V = []
    for k in range(0, 10):
        start_p = pos * delta + k * segment
        end_p = pos * delta + (k + 1) * segment
        if end_p > offset:
            end_p = offset

        listNN = []
        for j in range(start_p, end_p):
            listNN.append(gmpy2.sub(gmpy2.mul(gmpy2.add(_start, j), gmpy2.add(_start, j)), N))

        for i in range(0, n_smooth + 1):
            p = list_primes[i]
            index = 0
            for index in range(0, len(listNN)):
                if gmpy2.f_mod(listNN[index], p) == 0:
                    break
            index += start_p

            start_index1 = gmpy2.f_mod(index, p)

            for n in range(index - start_p, len(listNN), p):
                while gmpy2.f_mod(listNN[n], p) == 0:
                    listNN[n] = gmpy2.div(listNN[n], p)

            start_index2 = gmpy2.f_mod(gmpy2.sub(gmpy2.sub(p, gmpy2.f_mod(gmpy2.add(_start, start_index1), p)), _start),p)
            index2 = gmpy2.sub(p, gmpy2.f_mod(gmpy2.sub(start_p, start_index2), p))

            if start_index2 != start_index1:
                for n in range(index2, len(listNN), p):
                    while gmpy2.f_mod(listNN[n], p) == 0:
                        listNN[n] = gmpy2.div(listNN[n], p)

        for i in range(0, len(listNN)):
            if listNN[i] == 1:
                start1 = gmpy2.add(_start, start_p)
                num = gmpy2.sub(gmpy2.mul(gmpy2.add(start1, i), gmpy2.add(start1, i)), N)
                V.append(num)

    output.put((pos, V))
    print("end process " + str(pos))
Ejemplo n.º 31
0
def H_mpc(a,z):
    '''Returns generating function value. Takes in the a vector, the current position 
    on the parametrized variable t and the gamma function. Uses MPC and is
    not vectorized.'''
    temp=1
    n=len(a)
    for k in range(0,n):
        temp = gmpy2.div(temp, mpc((1-((z))**a[k])))
    return temp
Ejemplo n.º 32
0
def main():
    big = int(input("Big: "))
    small = int(input("Small: "))
    print("Sml Stat:", gmpy2.is_prime(small))

    result = gmpy2.div(big, small)
    print("Res Stat:", gmpy2.is_prime(result))

    print(result)
Ejemplo n.º 33
0
def main():
    start = time.clock()
    try:
	N_prime = mpz(mul(24,N))
	A_prime = isqrt(N_prime)+1
	x_prime = mpz(isqrt(pow(A_prime,2) - N_prime))
	p_prime = mpz(A_prime - x_prime)
	q_prime = mpz(A_prime + x_prime)
	assert mpz(mul(p_prime,q_prime)) == N_prime
	p = mpz(div(p_prime,6))
	q = mpz(div(q_prime,4))
	print 'p = ' + str(p)
	print 'q = ' + str(q)
	print 'Time: ' + str(time.clock() - start)
	assert mpz(mul(p,q)) == N
    except KeyboardInterrupt:
            print 'Keyboard interrupt!'
	    print 'Time: ' + str(time.clock() - start)
            sys.exit()
Ejemplo n.º 34
0
def factorial_div (one, two):
    '''
    computes a!/b!
    '''
    if one < two:
        return div(1., reduce (mul, xrange(one, two)))
    elif one > two:
        return reduce (mul, xrange(two, one))
    else:
        return mpfr (1.)
Ejemplo n.º 35
0
def factor(N):
    """
    :param N: mpz(N)
    :return: mpz(p), mpz(q)
    """
    N = gmpy2.mpz(N)
    A = ceil_sqrt(6 * N)
    a = 1
    b = -1
    c = -(A ** 2 - A - 6 * N)
    det = b ** 2 - 4 * a * c
    roots = (gmpy2.div(-b + gmpy2.isqrt(det), 2 * a), # 这里还非得用isqrt不能用sqrt了
             gmpy2.div(-b - gmpy2.isqrt(det), 2 * a))

    for x in roots:
        p = (A - x) // 3
        q = (A + x - 1) // 2
        if p * q == N:
            return p, q
Ejemplo n.º 36
0
def main():
    start = time.clock()
    try:
        N_prime = mpz(mul(24, N))
        A_prime = isqrt(N_prime) + 1
        x_prime = mpz(isqrt(pow(A_prime, 2) - N_prime))
        p_prime = mpz(A_prime - x_prime)
        q_prime = mpz(A_prime + x_prime)
        assert mpz(mul(p_prime, q_prime)) == N_prime
        p = mpz(div(p_prime, 6))
        q = mpz(div(q_prime, 4))
        print 'p = ' + str(p)
        print 'q = ' + str(q)
        print 'Time: ' + str(time.clock() - start)
        assert mpz(mul(p, q)) == N
    except KeyboardInterrupt:
        print 'Keyboard interrupt!'
        print 'Time: ' + str(time.clock() - start)
        sys.exit()
Ejemplo n.º 37
0
def factor2(n):
    avg_guess = gmpy2.isqrt(6 * n) + (0 if gmpy2.is_square(n) else 1)
    while True:
        a = gmpy2.mpz(1)
        b = gmpy2.mpz(1)
        c = 6 * n - avg_guess ** 2 + avg_guess
        x_roots = quadform(a, b, c)
        for x in x_roots:
            # Check for 3p < 2q
            p = gmpy2.div((avg_guess - x - 1), 3)
            q = gmpy2.div((avg_guess + x), 2)
            if (p * q == n):
                return (p, q)
            # Check for 3p > 2q
            p = gmpy2.div((avg_guess + x), 3)
            q = gmpy2.div((avg_guess - x - 1), 2)
            if (p * q == n):
                return (p, q)
        avg_guess += 1
Ejemplo n.º 38
0
def eea(a, b):
    r, r1 = a, b
    s, s1 = 1, 0
    t, t1 = 0, 1
    while r1 != 0:
        q = gmpy2.div(r, r1)
        r2 = gmpy2.f_mod(r, r1)
        r, s, t, r1, s1, t1 = r1, s1, t1, r2, gmpy2.sub(s, gmpy2.mul(s1, q)), gmpy2.sub(t, gmpy2.mul(t1, q))
    d = r
    return d, s, t
Ejemplo n.º 39
0
def mul_inv(a, b):
    b0 = b
    x0, x1 = 0, 1
    if b == 1: return 1
    while a > 1:
        q = gmpy2.div(a, b)
        a, b = b, a % b
        x0, x1 = x1 - gmpy2.mul(q, x0), x0
    if x1 < 0:
        x1 = gmpy2.add(x1, b0)
    return x1
    def swing(m, primes):
        if m < 33: return small_swing[m]

        s = bisect.bisect_left(primes, 1 + isqrt(m))
        d = bisect.bisect_left(primes, 1 + m // 3)
        e = bisect.bisect_left(primes, 1 + m // 2)
        g = bisect.bisect_left(primes, 1 + m)

        factors = primes[e:g]
        factors += filter(lambda x: div(m, x) & 1 == 1, primes[s:d])
        for prime in primes[1:s]:
            p, q = mpz(1), m
            while True:
                q = div(q, prime)
                if q == 0: break
                if q & 1 == 1:
                    p = mul(p, prime)
            if p > 1: factors.append(p)

        return product(factors, 0, len(factors) - 1)
    def swing(m, primes): 
        if m < 33: return small_swing[m] 
         
        s = bisect.bisect_left(primes, 1 + isqrt(m)) 
        d = bisect.bisect_left(primes, 1 + m // 3) 
        e = bisect.bisect_left(primes, 1 + m // 2) 
        g = bisect.bisect_left(primes, 1 + m) 
         
        factors = primes[e:g] 
        factors += filter(lambda x: div(m, x) & 1 == 1, primes[s:d]) 
        for prime in primes[1:s]:   
            p, q = mpz(1), m 
            while True: 
                q = div(q, prime )
                if q == 0: break 
                if q & 1 == 1: 
                    p = mul(p, prime )
            if p > 1: factors.append(p) 
 
        return product(factors, 0, len(factors) - 1) 
Ejemplo n.º 42
0
def verify_A3(A, N):
    '''
    serves factor_3
    '''
    c = -A**2 + A + 6 * N
    b = mpz(1)
    a = mpz(1)

    if (b**2 - 4 * a * c) < 0:
        return False

    x_candidates = (gmpy2.div((-b + gmpy2.isqrt(b**2 - 4 * a * c)), 2 * a),
                    gmpy2.div((-b - gmpy2.isqrt(b**2 - 4 * a * c)), 2 * a))

    for x in x_candidates:
        if x < 0:
            continue

        # 2q < 3p
        p = gmpy2.div((A + x), 3)
        q = gmpy2.div((A - x - 1), 2)
        if p * q == N:
            return p, q

        # 3p < 2q
        p = gmpy2.div((A - x - 1), 3)
        q = gmpy2.div((A + x), 2)
        if p * q == N:
            return p, q
    return False
Ejemplo n.º 43
0
def verify_A3(A, N):
    '''
    serves factor_3
    '''
    c = -A**2 + A + 6*N
    b = mpz(1)
    a = mpz(1)

    if (b**2 - 4*a*c) < 0:
        return False

    x_candidates = (
        gmpy2.div((-b + gmpy2.isqrt(b**2 - 4*a*c)), 2*a),
        gmpy2.div((-b - gmpy2.isqrt(b**2 - 4*a*c)), 2*a))

    for x in x_candidates:
        if x < 0:
            continue

        # 2q < 3p
        p = gmpy2.div((A + x), 3)
        q = gmpy2.div((A - x - 1), 2)
        if p*q == N:
            return p, q

        # 3p < 2q
        p = gmpy2.div((A - x - 1), 3)
        q = gmpy2.div((A + x), 2)
        if p*q == N:
            return p, q
    return False
Ejemplo n.º 44
0
def element_order_general(element, modulus, order, order_decomposition):
    if element == g.mpz(1):
        return 1  # by definition
    if g.powmod(element, order, modulus) != g.mpz(1):
        return None  # not an element of the group
    for factor, power in order_decomposition.items():
        for p in range(1, power + 1):
            next_order = g.div(order, factor)
            if g.powmod(element, next_order, modulus) == g.mpz(1):
                order = next_order
            else:
                break
    return order
Ejemplo n.º 45
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.º 46
0
def ch3_factor(N):
    """ Valid when |3p - 2q| < N^(1/4)
    """

    A = ceil_sqrt(6*N)

    # let M = (3p+2q)/2
    # M is not an integer since 3p + 2q is odd
    # So there is some integer A = M + 0.5 and some integer i such that
    # 3p = M + i - 0.5 = A + i - 1
    # and
    # 2q = M - i + 0.5 = A - i
    #
    # N = pq = (A-i)(A+i-1)/6 = (A^2 - i^2 - A + i)/6
    # So 6N = A^2 - i^2 - A + i
    # i^2 - i = A^2 - A - 6N 

    # Solve using the quadratic equation!
    a = mpz(1)
    b = mpz(-1)
    c = -(A**2 - A - 6*N)

    det = b**2 - 4*a*c

    roots = (div(-b + isqrt(b**2 - 4*a*c), 2*a),
         div(-b - isqrt(b**2 - 4*a*c), 2*a))


    for i in roots:
        if i >= 0:
            f = check_ch3(i,A,N)
            if f:
                return f

    # We should have found the root
    assert(False)
def create_gauss_matrix(V, list_primes):
    A = [[]]
    for i in range(0, len(V)):
        num = V[i]
        vector = []
        for p in range(0, n_smooth + 1):
            value = 0
            while gmpy2.c_mod(num, list_primes[p]) == 0:
                num = gmpy2.div(num, list_primes[p])
                value ^= 1
            vector.append(value)
        A.append(vector)

    print("cac so co the tao tich binh phuong: " + str(len(V)))
    print(V[:20])
    return A[1:]
Ejemplo n.º 48
0
def generate():
    r = 257
    while True:
        p = getPrime(1024)
        if (p - 1) % r == 0 and gcd(r, div(p - 1, r)) == 1:
            break
    while True:
        q = getPrime(1024)
        if gcd(r, q - 1) == 1:
            break
    n = p * q
    phi = (p - 1) * (q - 1)
    while True:
        y = getRandomRange(0, n)
        x = powmod(y, phi * invert(r, n) % n, n)
        if x != 1:
            break
    return (n, y), (n, phi, x)
Ejemplo n.º 49
0
def find_sqrt_ceil(N):
    lower_bound = mpz(2)
    upper_bound = N
    while True:
        times_two = mul(lower_bound, 2)
        if square(times_two) > N:
            upper_bound = times_two
            break
        else:
            lower_bound = times_two
    while True:
        middle = div(lower_bound + upper_bound, 2)
        if square(middle) == N:
            return middle
        elif square(middle) < N and square(middle + 1) > N:
            return middle + 1
        elif square(middle) < N:
            lower_bound = middle
        else:
            upper_bound = middle
Ejemplo n.º 50
0
    def find_factors3(self, N):
        A = gmpy2.isqrt(6 * N) * 2
        print("Origi A: ", A)

        x = gmpy2.div(A, 5)
        p = gmpy2.mul(x, 2)
        q = gmpy2.mul(x, 3)

        print("x: ", x)        
        print("p: ", p)
        print("q: ", q)

        product = gmpy2.mul(p, q)
        difference = gmpy2.sub(product, N)
        if difference == 0:
            print("Found A: ", A)
            print("p: ", p)
            print("q: ", q)
        print("product: ", product)
        print("difference: ", difference)
Ejemplo n.º 51
0
def rsa_mitm(n, e, c, b):
    S = random.randint(pow(2,b)/2 , pow(2,b))
    T = random.randint(pow(2,b)/2 , pow(2,b))
    n=gmpy2.mpz(n)
    cs=[gmpy2.mpz()]*(S)
    print S
    print T
    print n

    for s in range(1,S):
        cs[s] = gmpy2.mpz( gmpy2.c_mod(gmpy2.div(c,( gmpy2.powmod(s,e,n))) , n) )
        #print (s,cs[s])
    S_ = (T)/100
    for t in range(1,T):
        for s in range(1,S):
            if cs[s] == (gmpy2.powmod(t,e,n)):
                print (s,s*t)
                return s*t
    print cs
    return "Plaintext nicht gefunden"
Ejemplo n.º 52
0
def factors2(n):
    n = gmpy2.mpz(n)
    init_guess = gmpy2.isqrt(n)
    A = init_guess
    #    print('intial guess:')
    #    print(guess)
    #print('N2/guess:\n'+ str(int(N2/guess)) + '\nN2%guess:\n'+ str(int(N2%guess)))
    mindiv = n
    for i in range(1048576):
        x = gmpy2.sqrt(A**2 - n)
        p = A - x
        q = A + x
        mod = gmpy2.fmod(n, p)
        div = gmpy2.div(n, p * q)
        if div < mindiv:
            mindiv = div
        if not mod:
            print('p:\n' + str(int(p)))
            print('q:\n' + str(int(q)))
            break
        A += 1
Ejemplo n.º 53
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
Ejemplo n.º 54
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
Ejemplo n.º 55
0
 def test_binary(a, b):
     t = a + b
     t = a - b
     t = a * b
     try:
         t = a / b
     except:
         pass
     try:
         t = a // b
     except:
         pass
     try:
         t = divmod(a, b)
     except:
         pass
     t = gmpy2.add(a, b)
     t = gmpy2.sub(a, b)
     t = gmpy2.mul(a, b)
     t = gmpy2.div(a, b)
     t = gmpy2.agm(a, b)
     t = gmpy2.atan2(a, b)
Ejemplo n.º 56
0
def rsa_(n,e,c,b):
    T = pow(2,b)
    n=gmpy2.mpz(n)
    c=gmpy2.mpz(c)
    cs=[gmpy2.mpz()]*(T)
    # counter = 0
    # T_ = T/100
    # percent= 1
    for r in range(1,T):
        cs[r] = gmpy2.c_mod(gmpy2.div(c,gmpy2.powmod(r,e,n)),n)
        # counter += 1
        # if (counter >= T_):
        #     print percent
        #     percent +=1
        #     counter = 0
    #cs.sort()
    print cs
    for s in range (1, T):
        try:
            index=cs.index(gmpy2.powmod(s,e,n))
            #print (gmpy2.c_mod(index*s,n),cs[index],gmpy2.powmod(s,e,n) )
            return index*s
        except ValueError:
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 findFactorsCaseThree(self):
     print("===========================================")
     print("Modulus N is: " + str(self.N))
     #A = ceil(2 * sqrt(6N))
     A = gmpy2.ceil(gmpy2.mul(mpz(2), gmpy2.sqrt(gmpy2.mul(mpz(6), self.N))))
     print("A is: " + str(A))
     #X = sqrt(A^2 - 24N)
     A_square = gmpy2.mul(A, A)
     X = gmpy2.sqrt(gmpy2.sub(A_square, gmpy2.mul(mpz(24), self.N)))
     print("X is: " + str(X))
     #q = (A + X)/4 AND p = N/q
     self.q = gmpy2.f_div(mpz(gmpy2.add(A, X)), mpz(4))
     self.p = gmpy2.div(self.N, self.q)
     prod = gmpy2.mul(self.p, self.q)
     print("Product of pq is: " + str(prod))
     if prod == self.N:
         print("We have got the factors RIGHT")
     else:
         print("We didn't get the factors")
         print(self.p)
         print(self.q)
         self.p = 0
         self.q = 0
     print("===========================================")
 def odd_factorial(n, primes): 
     if n < 2: return 1 
     tmp = odd_factorial(div(n, 2), primes)
     return mul(mul(tmp, tmp), swing(n, primes)) 
Ejemplo n.º 60
0
def quadform(a, b, c):
    det = gmpy2.isqrt(b ** 2 - 4 * a * c)
    r1 = gmpy2.div((-b + det), 2 * a)
    r2 = gmpy2.div((-b - det), 2 * a)
    return (r1, r2)