Exemplo n.º 1
0
def checkFactors(p,q,N):
  x = g.f_mod( N, p )
  y = g.f_mod( N, q )
  zero = g.mpz('0')
  if g.is_prime(p) and g.is_prime(q):
    return N == g.mul(p,q) and x == zero and y == zero
  return False
Exemplo n.º 2
0
    def digitial_generation(self,message,Curve_Polynomial,X,Y,Order,A,d_A):
        r=np.array([0x0],dtype='uint32')
        m=hashlib.sha256(message).hexdigest()
        
        Order_np = self.str2nparray(Order) 
        Order_int = int(Order,16)
        
        l=(len(Order_np)-1)*32+gmpy2.bit_length(int(Order_np[-1]))
     
        m = field.str2nparray(m)
        size = l/32+1
        m=self.remove_1(m)
   
        if(l>=256):
            rem=l-256
            chunk_added=(rem/32)+1
            m=np.append(np.zeros(chunk_added,dtype='uint32'),m)
            part=32-(l+chunk_added)%32
        else:
            m = m[len(m)-size:]
            part = 32-l%32

        X1=m>>part
        Y1=m<<(32-part)
        Z=np.bitwise_xor(Y1[1:],X1[:-1])
        Z=np.append(Z,X1[-1])
        
        Z = self.nparray2str(Z)
        Z = int(Z,16)
        
        Z = gmpy2.f_mod(Z,Order_int)
        S=0
        
        while(S==0):
            while(np.all(r[0]==0)):
                k=random.randint(1,Order_int-1)
                r=self.bin_public_key_gen(X,Y,A,k)

            k_inv=gmpy2.invert(k,Order_int)

            r = self.nparray2str(r[0])
            r = int(r,16)
            r=gmpy2.f_mod(r,Order_int)
            rd_A = gmpy2.mul(r,d_A)
            rd_A = gmpy2.f_mod(rd_A,Order_int)


            Zrd_A = rd_A + Z

            Zrd_A = int(Zrd_A)
            k_inv = int(k_inv)

            S = gmpy2.mul(Zrd_A,k_inv)
            S = gmpy2.f_mod(S,Order_int)

        
 
        
        return r,S
Exemplo n.º 3
0
    def digitial_Verification(self,message,Order,X,Y,A,d_A,r,S):
        
        
        X=self.str2nparray(X)
        Y=self.str2nparray(Y)

        A=self.str2nparray(A)
        
        m=hashlib.sha256(message).hexdigest()
      
        Order_np = self.str2nparray(Order) 
        Order_int = int(Order,16)
        
        l=(len(Order_np)-1)*32+gmpy2.bit_length(int(Order_np[-1]))
      
        m = field.str2nparray(m)
        size = l/32+1
        m=self.remove_1(m)
 
        if(l>=256):
            rem=l-256
            chunk_added=(rem/32)+1
            m=np.append(np.zeros(chunk_added,dtype='uint32'),m)
            part=32-(l+chunk_added)%32
        else:
            m = m[len(m)-size:]
            part = 32-l%32

        X1=m>>part
        Y1=m<<(32-part)
        Z=np.bitwise_xor(Y1[1:],X1[:-1])
        Z=np.append(Z,X1[-1])
        
        Z = self.nparray2str(Z)
        Z = int(Z,16)
        Z = gmpy2.f_mod(Z,Order_int)                               #####Truncated Message
        
        w=gmpy2.invert(S,Order_int) 
        
        u1 = gmpy2.mul(Z,w)
        u1 = gmpy2.f_mod(u1,Order_int)
       
        u2 = gmpy2.mul(r,w)
        u2 = gmpy2.f_mod(u2,Order_int)
      
        Q_A=self.public_key_gen(X,Y,A,d_A)   #Q_A = d_A * G    
 
       
        X1=self.public_key_gen(X,Y,A,int(u1))
        X2=self.public_key_gen(Q_A[0],Q_A[1],A,int(u2))    #u2*Q_A
        X3=self.point_add(X1[0],X1[1],X2[0],X2[1],A)
        X3=self.nparray2str(X3[0])
        X3 = gmpy2.f_mod(int(X3,16),Order_int)
        
        #print X3[0]
        
        return X3
def create_primes_index(list_primes):
    list_start_index = []
    for i in range(0, n_smooth + 1):
        p = list_primes[i]
        sqr1 = sqrt_modulo.sqrt_modular(N, p)
        sqr2 = p - sqr1
        start_index1 = gmpy2.f_mod(gmpy2.sub(sqr1 - start), p)
        start_index2 = gmpy2.f_mod(gmpy2.sub(sqr2 - start), p)
        list_start_index.append([start_index1, start_index2])
    return list_start_index
Exemplo n.º 5
0
def mypowmod(a, b, N):
    ret = 1
    while b > 0:
        if b & 1 == 1:
            ret = gmpy2.mul(ret,a)
            ret = gmpy2.f_mod(ret,N)
        a = gmpy2.mul(a,a)
        a = gmpy2.f_mod(a,N)
        b = b >> 1
    return gmpy2.f_mod(ret,N)
Exemplo n.º 6
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
Exemplo n.º 7
0
    def create_left_side_hash(self):
        dict = {}
        search_space = pow(2, SEARCH_SPACE_EXPONENT)

        for i in range(1, search_space):
            left_side_value = gmpy2.f_mod( (HVALUE * gmpy2.powmod(GENERATOR, -i, PRIME)), PRIME)
            dict[left_side_value] = i

            if gmpy2.f_mod(i, 100000) == 0:
                print i

        return dict
Exemplo n.º 8
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)
Exemplo n.º 9
0
def hash_table(h, g, p, B):
    table = dict()  # Table to store x1 and h/(g**x1) values
    for x1 in range(B - 1):
        val = gmpy2.f_mod(gmpy2.mul(h, gmpy2.powmod(g, -x1, p)), p)
        table.update({val: x1})

    return table
Exemplo n.º 10
0
def findx(table,numiter):
	

	gb = gmpy2.f_mod(pow(g1,numiter),p1)
	res = gb
	for i in range(0,numiter+1):
		if i == 0:
			aux = 1
		else:
			aux = gmpy2.f_mod(gmpy2.mul(res,gb),p1)

		res = aux		
		if aux in hashtable:
			x1 = hashtable[aux]
			x = i * numiter + x1
			print "x=", x
Exemplo n.º 11
0
def gen_hash_table(numiter):
	hash_table = {}
	hash_table[0] = gmpy2.f_mod(h1,p1)

	r = gmpy2.divm(h1,g1,p1)
	aux2 = gmpy2.divm(mpz(1),g1,p1)
	for i in range(1,numiter+1):
		
		if i == 1:
			aux = gmpy2.f_mod(gmpy2.mul(r,1),p1)
		else:
			aux = gmpy2.f_mod(gmpy2.mul(r,aux2),p1)
		
		hash_table[aux] = i
		r = aux
	return hash_table
Exemplo n.º 12
0
    def check_right_side_against_hash(self, hashed_left_data):
        search_space = pow(2, SEARCH_SPACE_EXPONENT)

        for i in range(1, search_space):
            e = search_space * i
            right_side_result = gmpy2.powmod(GENERATOR, e, PRIME)

            if right_side_result in hashed_left_data:
                print("x1: ", i)
                print("x0: ", hashed_left_data[right_side_result])

                final_answer = gmpy2.f_mod(( (i * search_space) + hashed_left_data[right_side_result]), PRIME)
                print("x0 * B + x1 mod p: ", final_answer)

                print("Check final answer: ", gmpy2.powmod(GENERATOR, final_answer, PRIME))
                return

            if gmpy2.f_mod(i, 100000) == 0:
                print("Checked: ", i)
Exemplo n.º 13
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
Exemplo n.º 14
0
def findLog():
    leftSide = {}
    for x1 in range(0,middleSize):
        leftSide[calculateLeft(x1)] = x1
    for x0 in range(0,middleSize):
        num = calculateRight(x0)
        if num in leftSide:
            print "x0: ", x0
            print "x1: ", leftSide[num]
            print "x: ", gmpy2.f_mod(gmpy2.mul(x0*middleSize)+leftSide[num],p)
            break
Exemplo n.º 15
0
def probable_prime(prime, i):
    for k in range(0,10000000):
        p = prime + k

        # check to see if p is prime
        a = gmpy2.powmod(2, p-1, p)
        # check to see if 3 divides into prime - 1
        b = gmpy2.mpz(gmpy2.f_mod(p-1, 3))

        if (a == 1 and b == 1): 
            print "k_%i = %i" %(i, k)
            print "p_%i = %i" %(i, p)
            return p
Exemplo n.º 16
0
def run(p,g,h):
    B=mpz(2**20)
    limit = B+1
    g = gmpy2.f_mod(g,p)
    hashd={}
    st = time.time()
    for x1 in xrange(limit+1):
        hashd[ gmpy2.f_mod( h* gmpy2.powmod(g,-x1,p) ,p) ] =x1
    #        if gmpy2.f_mod( h* gmpy2.powmod(g,-x1,p) ,p) <> 
    #gmpy2.f_mod( gmpy2.f_div( h, gmpy2.powmod(g,x1,p) ),p):
    #            print x1
    g_pow_B = gmpy2.powmod(g,B,p)
    print 'finished stage A',time.time()-st
    print len(hashd)
    st = time.time()
    for x0 in xrange(limit+1):
        rhs = gmpy2.powmod(g_pow_B,x0,p)
        if  rhs in hashd:
            x1=hashd[rhs]
            x0,x1 = mpz(x0),mpz(x1)
            print x0,x1,gmpy2.f_mod(x0*B+x1,p),x0*B+x1
    print 'finished stage B',time.time()-st
Exemplo n.º 17
0
def compute_discrete_log(p, h, g, B):
    map = {}
    g_to_the_B = powmod(g, B, p)
    for x0 in range(1, 2 ** 20):
        map[powmod(g_to_the_B, x0, p)] = x0

    print("Done with step 1!")

    for x1 in range(1, 2 ** 20):
        g_to_x1 = powmod(g, x1, p)
        left_hand = f_mod(invert(g_to_x1, p) * h, p)
        if map.get(left_hand) is not None:
            x0 = map.get(left_hand)
            print((x0, x1, B))
            return mpz(x0) * B + mpz(x1)

    return "No luck"
Exemplo n.º 18
0
def compute_hash_table(h, g, p):
    """
    :param h: 22
    :param g: 43
    :param p: 35
    :return: {mpz(8): 2, mpz(1): 3, mpz(29): 1, mpz(22): 0}
    """
    hash_table = dict()
    for x1 in range(2 ** 20 + 1):
        denominv = pow(g, x1, p)  # 计算分母
        denom = gmpy2.invert(denominv, p)  # 计算1/分母
        tval = gmpy2.mul(h, denom)  # 计算h * 1/分母
        res = gmpy2.f_mod(tval, p)  # 对p求模

        hash_table.setdefault(res, x1)

    return hash_table
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))
Exemplo n.º 20
0
    def decrypt(c, lbd, mu, n):
        """
        Decrypts encrypted number c with respect to private keys
                 lambda and mu (and public key n)
        
        Parameters:
            m: number to be encrypted
            lbd,mu: private keys used for the decryption
            n: public key necessary for decryption
        Returns:
            c: encrypted representation of m
        """
        n2 = pow(n, 2)
        one = gmpy2.mpz(1)
        x = gmpy2.sub(gmpy2.powmod(c, lbd, n2), one)
        m = gmpy2.f_mod(gmpy2.mul(gmpy2.f_div(x, n), mu), n)

        if m >= gmpy2.f_div(n, 2):
            m = m - n
        return m
Exemplo n.º 21
0
    def verifyByCode(self, vArr, verbal):
        randomVec = [
            int(gmpy2.mpz_random(self.rs, self.order))
            for i in range(self.n - self.t)
        ]
        codewordInDual = self.code.getCodewordInDual(randomVec)
        codewordInDual = [
            gmpy2.f_mod(mpz(int(ele)), self.order) for ele in codewordInDual
        ]
        if verbal: print "Random codeword from dual : " + tostr(codewordInDual)
        if verbal: print "Intermediates"

        product = (0L, 0L)
        for vi, ci in zip(vArr, codewordInDual):
            temp = ec.multiply(vi, ci)
            if verbal: print str(ci) + " x " + tostr(vi) + " = " + tostr(temp)
            product = ec.add(product, temp)
        if verbal: print "Product : " + tostr(product)
        if product == (0L, 0L):
            if verbal: print "...Codeword valid : v"
Exemplo n.º 22
0
 def F_x(self,k,lsc,lc):#lsc是s的系数列表,lc是常数项列表
     Fk = list()
     Fc = gmpy2.mpz(1)
     self.Fkg = list()
     qm = gmpy2.mpz(730750818665451621361119245571504901405976559617)
     for i in range(k):
         Fc = Fc * lsc[i]
         temp1 = gmpy2.divm(gmpy2.mpz(1),lsc[i],qm)
         lc[i] = gmpy2.mul(lc[i],temp1)
         #lsc[i] = gmpy2.mpz(1)
     for i in range(k):
         p = np.poly1d([gmpy2.mpz(1),lc[i]])
         #print(p)
         Fk.append(p)
     temp = Fk[0]
     for j in range(1,k):
        temp = temp * Fk[j]
     self.Fkg = list(temp.coef)
     for n in range(k):
         self.Fkg[n] = self.Fkg[n] * Fc
         self.Fkg[i] = gmpy2.f_mod(self.Fkg[i],q)
Exemplo n.º 23
0
    def encrypt(m, n, g):
        """
        Encrypts a message, given a public key.
        
        Parameters:
            m: number to be encrypted
            n,g: public keys used for the decryption
        Returns:
            c: encrypted representation of m
        """
        n2 = pow(n, 2)
        one = gmpy2.mpz(1)
        state = gmpy2.random_state(int_time())
        r = gmpy2.mpz_random(state, n)
        while gmpy2.gcd(r, n) != one:
            state = gmpy2.random_state(int_time())
            r = gmpy2.mpz_random(state, n)

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

        return c
Exemplo n.º 24
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
Exemplo n.º 25
0
    def __init__(self, a_in, b_in, p_in):
        self.a = mpz(a_in)
        self.b = mpz(b_in)
        self.p = mpz(p_in)
        self.generator = (0, 0)
        self.field = []
        self.sqrtCheats = {mpz(0): mpz(0)}
        self.q = 0
        for i in range(1, self.p // 2 + 1):
            sq = gmpy2.f_mod(mpz(i * i), self.p)
            self.sqrtCheats[sq] = mpz(i)
        #print self.sqrtCheats
        self.points = []

        for i in range(self.p):
            x = mpz(i)
            y = self.findY(x)
            if y != None:
                if y == 0:
                    self.points.append((x, y))
                else:
                    self.points += [(x, y), (x, self.p - y)]
Exemplo n.º 26
0
Arquivo: PVSS.py Projeto: dat96le/rng
def findFactoredNeighboredPrime(nbits):
    rs = gmpy2.random_state(gmpy2.f_mod(mpz(time.time()), 60))
    m = mpz(2**(nbits - 1))
    test = mpz(1)
    while not gmpy2.is_prime(test + 1) or test < mpz(2**(nbits - 1)):
        seq = [m]
        temp = m
        # Algorithm 9.5, V.Shoup
        # constructs a random non-increasing sequence with m as maximum
        while temp > 1:
            temp = gmpy2.mpz_random(rs, temp) + 1
            seq.append(temp)
        test = mpz(1)
        seq.reverse()
        primes = []

        for num in seq:
            if gmpy2.is_prime(num):
                test *= num
                primes.append(num)
                if test > 2**(nbits - 1):
                    break

    return (test + 1, primes)
Exemplo n.º 27
0
    def Gen_response(self,slist,split_ID,hksplit_ID):#t代表多项式的项数,n代表分片的数量
        pairing = global_variable.get_pairing()
        g1 = global_variable.get_g1()
        self.__response = gmpy2.mpz(0)
        coef_hk = dict()
        for i in range(len(slist)-2):
            temp = slist[i]
            temp1 = hksplit_ID[len(slist)-1-i]
            temp2 = gmpy2.mul(temp , temp1)
            temp2 = gmpy2.f_mod(temp2,q)
            coef_hk[i+2] = temp2
        #存m个f(i)+a[i]连乘的结果
        fk_ID = (np.polyval(slist,split_ID))
        fk_ID = fk_ID % q
        for l in coef_hk:
            coefhk = coef_hk[l]
            fk_ID = gmpy2.sub(fk_ID , coefhk)
            fk_ID = fk_ID % q
        self.__response = fk_ID

        
        self.__comm_response_ID = Element(pairing, G1)
        self.__comm_response_ID = g1 ** int(self.__response)
        return self.__comm_response_ID,self.__response
Exemplo n.º 28
0
 def check_delta(self):
     """"check delta condidtion with definition, gcd(delta, n) = 1"""
     return f_mod((4 * (self.A * self.A * self.A) + 27 *
                   (self.B * self.B)), self.P) != 0
Exemplo n.º 29
0
def mpz_mod_modified(op1, op2):
    rop = gmpy2.f_mod(mpz(op1), mpz(op2))
    temp = gmpy2.f_div(mpz(op2), two)
    if rop > temp:
        rop = gmpy2.sub(rop, mpz(op2))
    return rop
Exemplo n.º 30
0
    def check_point(self, X, Y):
        """"Check if point belong to this curve 
			Y^2 == X^3 + A*X + B
        """
        return f_mod((Y * Y), self.P) == f_mod(
            (X * X * X + self.A * X + self.B), self.P)
Exemplo n.º 31
0
import gmpy2
from timeit import default_timer as timer
start=timer()
p=gmpy2.mpz(13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171)
g=gmpy2.mpz(11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568)
h=gmpy2.mpz(3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333)
print(p+g)
PA={}
B=gmpy2.mpz(2**20)
index=[]
for i in range(1,2**20):#2**20):
    guess=gmpy2.f_mod( gmpy2.mul(gmpy2.invert( gmpy2.powmod(g,i,p),p),h),p)
    #table[guess%B].append(guess%p)
    #table[guess%B].append(i)
    PA[guess]=i
    
for j in range(1,2**20):
    result=gmpy2.powmod(g,B*j,p)
    if result in PA:
        print("Found X=",PA[result]+j*B)
        break
end=timer()
print(end-start)
Exemplo n.º 32
0
77723561443721764030073546976801874298166903427690031\
858186486050853753882811946569946433649006084171')

g = mpz('11717829880366207009516117596335367088558084999998952205\
59997945906392949973658374667057217647146031292859482967\
5428279466566527115212748467589894601965568')

h = mpz('323947510405045044356526437872806578864909752095244\
952783479245297198197614329255807385693795855318053\
2878928001494706097394108577585732452307673444020333')

B = 2 ** 20
hash = {}

print 'start building...'

for x1 in range(B):
	if x1 % 10000 == 0:
		print '%d completed.' % x1
	left = f_mod(h * powmod(g, -x1, p), p)
	hash[left] = x1
	
for x0 in range(B):
	if x0 % 10000 == 0:
		print '%d completed.' % x0
	right = powmod(g, x0 * B, p)
	if right in hash:
		x = x0 * B + hash[right]
		print 'Solution:\t', x
		break
		
Exemplo n.º 33
0
 def recover_poly(self, split, t, userid):
     poly_coef_up = dict()
     poly_coef_down = list()
     poly_coef = dict()
     qm = gmpy2.mpz(730750818665451621361119245571504901405976559617)
     for i in range(t):
         coef_of_variable = list()
         coef_of_constant = list()
         akcoef1 = list()
         temp1 = 1
         for j in range(t):
             if j != i:
                 coef_of_variable.append(1)
                 coef_of_constant.append(-(userid[j + 1]))
         coef = self.__F_x(len(coef_of_variable), coef_of_variable,
                           coef_of_constant)
         poly_coef_up[i + 1] = coef
         for m in range(t):
             akcoef1.append(userid[m + 1])
         for m in range(t):
             if m != i:
                 temp1 = gmpy2.mul(temp1,
                                   (gmpy2.sub(akcoef1[i], akcoef1[m])))
                 temp1 = gmpy2.f_mod(temp1, q)
         poly_coef_down.append(temp1)
     for i in range(t):
         poly_coef_up_i = poly_coef_up[i + 1]
         poly_coef_down_i = poly_coef_down[i]
         temp4 = list()
         for j in range(len(poly_coef_up_i)):
             poly_coef_up_i[0] = gmpy2.mpz(1)
             temp2 = poly_coef_up_i[j]
             temp3 = gmpy2.divm(temp2, poly_coef_down_i, qm)
             temp4.append(temp3)
         poly_coef[i + 1] = temp4
     split_recover = list()  #存用于恢复多项式的分片
     __recover_poly_coef = list()  #恢复后的多项式系数
     split_mul_poly = dict()
     m = 0
     for i in range(t):
         m += 1
         if m <= 3:
             split_recover.append(split[akcoef1[i]])
     for i in range(t):
         temp7 = list()
         temp5 = poly_coef[i + 1]
         for j in range(len(temp5)):
             temp6 = gmpy2.mul(split_recover[i], temp5[j])
             temp6 = gmpy2.f_mod(temp6, q)
             temp7.append(temp6)
         split_mul_poly[i] = temp7
     __recover_poly_coef = split_mul_poly[0]
     for i in range(t):
         if i != 0:
             temp = split_mul_poly[i]
             for j in range(len(__recover_poly_coef)):
                 __recover_poly_coef[j] = gmpy2.add(__recover_poly_coef[j],
                                                    temp[j])
                 __recover_poly_coef[j] = gmpy2.f_mod(
                     __recover_poly_coef[j], q)
     __secret_of_poly = np.polyval(__recover_poly_coef, 0)  #由恢复出来的多项式得到的秘密值
     __secret_of_poly = gmpy2.f_mod(__secret_of_poly, qm)
     return __recover_poly_coef, __secret_of_poly
Exemplo n.º 34
0
def calculateRight(x0):
    power = pow(g,gmpy2.mul(middleSize , x0),p)
    return gmpy2.f_mod(power,p)
Exemplo n.º 35
0
 def mod(self, a):
     return gmpy2.f_mod(a, self.Prime)
 def add(self, x, y):
     sum = gmpy2.f_mod(gmpy2.mul(x, y), self.N * self.N)
     return sum
Exemplo n.º 37
0
 print("======g=0(mod q)=======")
 g=0
 k=147
 x1=1331
 x2=3131
 m1="Hello,world"
 m2="Goodbye,world"
 a=sha.new()
 h1=a.update(m1)
 h1=a.hexdigest()
 a=sha.new()
 h2=a.update(m2)
 h2=a.hexdigest()
 c=DSA()
 r=c.calcR(k,p,q)
 s1=gmpy2.f_mod(gmpy2.mpz(gmpy2.mul(gmpy2.invert(k,q),gmpy2.add(int(h1,16),gmpy2.mul(x1,r)))),q)
 s2=gmpy2.f_mod(gmpy2.mpz(gmpy2.mul(gmpy2.invert(k,q),gmpy2.add(int(h1,16),gmpy2.mul(x2,r)))),q)
 print "当x=1331,s等于:"+str(s1)
 print "当x=3131,s等于:"+str(s2)
 print "可见签名与私钥无关!"
 s3=gmpy2.f_mod(gmpy2.mul(gmpy2.mul(gmpy2.invert(k,q),(int(h1,16))),gmpy2.mul(gmpy2.invert(int(h1,16),q),int(h2,16))),q)
 s4=gmpy2.f_mod(gmpy2.mpz(gmpy2.mul(gmpy2.invert(k,q),gmpy2.add(int(h2,16),gmpy2.mul(x2,r)))),q)
 print "由hello,world的伪造的签名(s)值:"+str(s3)
 print "计算goodbye,world的签名(s)值:"+str(s4)
 print "伪造成功!"
 print("\n======g=1(mod q)=======")
 g=p+1
 y=gmpy2.powmod(g,k,p)
 import random
 z=random.randint(1,1301019)
 print "对任意z都成立!"
Exemplo n.º 38
0
    def __Gen_vk(self, t, n, k):
        #获取全局变量
        pairing = global_variable.get_pairing()
        g1 = global_variable.get_g1()

        #生成秘密 secret 的承诺
        secret_k = dict()
        secret = self.__f[0]
        temp = secret
        secret_k[1] = secret
        for i in range(k):
            if i >= 1:
                temp = gmpy2.mul(temp, secret)
                temp = gmpy2.f_mod(temp, q)
                secret_k[i + 1] = temp
        commitment_s_i = Element(pairing, G1)
        self.__commitment_s = dict()
        for i in secret_k:
            commitment_s_i = g1**int(secret_k[i])
            self.__commitment_s[i] = commitment_s_i
        #print ("commitment_s = \n",self.__commitment_s)

        #生成 f(x) 的承诺
        commitment_fx_coef = self.__comm(self.__f, 1, t, pairing, g1)
        print("the commitment of fx = \n", commitment_fx_coef)
        self.__commitment_fx_joint = str(commitment_fx_coef[0])
        for i in range(t - 1):
            self.__commitment_fx_joint = self.__commitment_fx_joint + str(
                commitment_fx_coef[i + 1])
        #print("the joint of fx = \n",self.__commitment_fx_joint)

        #生成 r
        self.__r = 0
        r = sha256()
        r.update(self.__commitment_fx_joint.encode("utf8"))
        dr = r.hexdigest()
        self.__r = int(dr, 16)
        self.__r = gmpy2.mpz(self.__r)
        self.__r = gmpy2.f_mod(self.__r, q)
        #print("r = \n",self.__r)

        #生成 f(r) 和 f(r)^k 的承诺
        self.__commitment_fr_k = dict()
        fr = self.__fun(self.__f, 1, t, self.__r)
        comm_fr = Element(pairing, G1)
        comm_fr = g1**int(fr)
        self.__commitment_fr_k[1] = comm_fr
        fr_i = fr
        for i in range(k - 1):
            fr_i = fr_i * fr
            comm_fr_i = Element(pairing, G1)
            comm_fr_i = g1**int(fr_i)
            self.__commitment_fr_k[i + 2] = comm_fr_i
        print("commitment_fr_k = \n", self.__commitment_fr_k)

        #生成 ck(x) 的承诺
        commitment_ck_coef = dict()
        self.__commitment_ck_joint = dict()
        for i in self.__ck:
            commitment_ck_i = list()
            ck_i = self.__ck[i]
            commitment_ck_i = self.__comm(ck_i, 1, t, pairing, g1)
            commitment_ck_coef[i] = commitment_ck_i
        #print("commitment_ck_coef = \n", commitment_ck_coef)
        for i in commitment_ck_coef:
            comm_ci_coef = commitment_ck_coef[i]
            str_comm_ci_coef = str(comm_ci_coef[0])
            str_comm_ci_coef = str_comm_ci_coef[:130]
            for j in range(t - 1):
                str_comm_ci_coef = str_comm_ci_coef + str(comm_ci_coef[j + 1])
            self.__commitment_ck_joint[i] = str_comm_ci_coef
        #print("commitment_ck_joint = \n",self.__commitment_ck_joint)

        #生成 hk(x) 的承诺
        commitment_hk_coef = dict()  #用于存储基点与hk各个系数的点乘结果
        self.__commitment_hk_joint = dict()  #用于存储拼接后的hk的承诺
        for i in self.__hk:
            commitment_hk_i = list()
            hk_i = self.__hk[i]
            commitment_hk_i = self.__comm(hk_i, i, t, pairing, g1)
            commitment_hk_coef[i] = commitment_hk_i
        #print("commitment_hk_coef = \n",commitment_hk_coef)
        for i in commitment_hk_coef:
            comm_hi_coef = commitment_hk_coef[i]
            str_comm_hi_coef = str(comm_hi_coef[0])
            str_comm_hi_coef = str_comm_hi_coef[:130]
            for j in range(i * t - i):
                str_comm_hi_coef = str_comm_hi_coef + str(comm_hi_coef[j + 1])
            self.__commitment_hk_joint[i] = str_comm_hi_coef
        #print("commitment_hk_joint = \n",self.__commitment_hk_joint)

        #生成 f(x) 分片 f(i) 的承诺,用于安全传输
        self.__commitment_split = dict()
        for i in self.__split:
            comm_split = Element(pairing, G1)
            comm_split = g1**int(self.__split[i])
            self.__commitment_split[i] = comm_split
        #print("commitment_split = \n",self.__commitment_split)

        #生成 hk(x) 分片 hk(i) 的承诺,用于安全传输
        self.__commitment_hk_split = dict()
        for i in self.__hksplit:
            hksplit_key = self.__hksplit[i]
            comm_hksplit_key = dict()
            for key in hksplit_key:
                comm_hksplit = Element(pairing, G1)
                comm_hksplit = g1**int(hksplit_key[key])
                comm_hksplit_key[key] = comm_hksplit
            self.__commitment_hk_split[i] = comm_hksplit_key
Exemplo n.º 39
0
def calculateLeft(x1):
    denominv =  gmpy2.f_mod(pow(g, x1,p),p)
    denom = gmpy2.invert(denominv, p)
    tval = gmpy2.mul(h, denom)
    return gmpy2.f_mod(tval, p)
Exemplo n.º 40
0
def random_from_interval(random_state, low, high, m=32):
    M = int(g.ceil(g.log2(high)))
    random = g.mpz_urandomb(random_state, M + m)
    c = g.add(g.f_mod(random, g.add(g.sub(high, low), 1)), low)
    return c
Exemplo n.º 41
0
77723561443721764030073546976801874298166903427690031\
858186486050853753882811946569946433649006084171')

g = mpz('11717829880366207009516117596335367088558084999998952205\
59997945906392949973658374667057217647146031292859482967\
5428279466566527115212748467589894601965568')

h = mpz('323947510405045044356526437872806578864909752095244\
952783479245297198197614329255807385693795855318053\
2878928001494706097394108577585732452307673444020333')

B = 2**20
hash = {}

print 'start building...'

for x1 in range(B):
    if x1 % 10000 == 0:
        print '%d completed.' % x1
    left = f_mod(h * powmod(g, -x1, p), p)
    hash[left] = x1

for x0 in range(B):
    if x0 % 10000 == 0:
        print '%d completed.' % x0
    right = powmod(g, x0 * B, p)
    if right in hash:
        x = x0 * B + hash[right]
        print 'Solution:\t', x
        break
                           data_1_to_2_queue, data_1_to_3_queue, q12, q13)
    d_paillier.distributed_RSA_modulus_generation()
    stop = time.time()
    print("RSA modulus generation success")
    print("modulus = ", d_paillier.N)
    print("duration = ", stop - start, "seconds")
    d_paillier.distributed_Paillier_key_generation()

    # decryption and encryption
    m1 = 464313146
    m2 = 976311987
    m3 = 598188167
    print("m1 = ", m1)
    print("m2 = ", m2)
    print("m3 = ", m3)
    print("(m1 + m2) * m3 % N = ", gmpy2.f_mod((m1 + m2) * m3, d_paillier.N))
    c1 = d_paillier.encrypt(m1)
    c2 = d_paillier.encrypt(m2)
    c3 = d_paillier.encrypt(m3)
    ciphertext = d_paillier.mul(d_paillier.add(c1, c2),
                                m3)  # (m1 + m2) * m3 % N
    d_paillier.send_ciphertext(ciphertext)

    partial_decryption = d_paillier.partial_decrypt(ciphertext)
    print("partial decryption = ", partial_decryption)
    d_paillier.send_partial_decryption(partial_decryption)
    partial_decryption_list = d_paillier.rec_partial_decryption_list(
        partial_decryption)
    decrypted_massage = d_paillier.combine_partial_decrypt(
        partial_decryption_list)
    print("decrypted massage = ", decrypted_massage)
Exemplo n.º 43
0
    def __Gen_polynomial(self, t, k):
        #生成 f(x)

        self.__f = list()  #用于存储f(x)的系数
        secret = random.randint(0, 2**255)
        secret = gmpy2.mpz(secret)
        #print("secret = \n",secret)
        self.__f.append(secret)
        for i in range(t - 1):  #f(x)多项式的其他系数
            fki = random.randint(0, 2**255)
            fki = gmpy2.mpz(fki)
            self.__f.append(fki)
        for i in range(t):
            self.__f[i] = gmpy2.f_mod(self.__f[i], q)
        #print("f = \n",self.__f)

        #生成 ck(x), k 取值为2,,,k,将某个 ck 的系数存在列表中,将生成的所有 ck(x) 存在字典中

        self.__ck = dict()
        for i in range(k + 1):
            if i > 1:
                cki = list()
                cki.append(gmpy2.mpz(0))
                for j in range(t - 1):
                    ckii = random.randint(0, 2**255)
                    ckii = gmpy2.mpz(ckii)
                    cki.append(ckii)
                for l in range(t):
                    cki[l] = gmpy2.f_mod(cki[l], q)
                self.__ck[i] = cki
        #print("ck = \n",self.__ck)

        #生成 fk(x), k 取值为 2,,,k,将某个 fk 的系数存在列表中,将生成的所有 fk(x) 存在字典中
        self.__fk = dict()
        for m in range(k + 1):  #生成f^2(x)至f^k(x),m表示生成f(x)的m次方
            if m > 1:
                fki = [0] * (m * t - m + 1)
                for i in range(t):
                    fki[i] = self.__f[i]
                for j in range(m - 1):
                    fktemp = [0] * (m * t - m + 1)
                    for p in range((m - 1) * t - m + 2):
                        for l in range(t):
                            temp = gmpy2.mul(fki[p], self.__f[l])
                            fktemp[p + l] = gmpy2.add(fktemp[p + l], temp)
                    for w in range(m * t - m + 1):
                        fki[w] = gmpy2.f_mod(fktemp[w], q)
                self.__fk[m] = fki
        #print("fk = \n",self.__fk)

        #计算 h^k(x),并将系数存在字典中
        self.__hk = dict()
        fk1 = list()
        ck1 = list()
        for i in self.__fk:  #取出字典中的列表进行h^k(x)的计算
            hki = list()
            fk1 = self.__fk[i]
            ck1 = self.__ck[i]
            for j in range(t):
                temp = gmpy2.sub(fk1[j], ck1[j])
                hki.append(temp)
            for l in range((i - 1) * t - i + 1):
                hki.append(fk1[t + l])
            hki[0] = gmpy2.sub(hki[0], self.__f[0]**i)
            for m in range(i * t - i + 1):
                hki[m] = gmpy2.f_mod(hki[m], q)
            self.__hk[i] = hki
Exemplo n.º 44
0
 def mul(self, a, b):
     return gmpy2.f_mod(gmpy2.mul(a, b), self.Prime)
Exemplo n.º 45
0
    if rsa_dec(Cipher, prv) != m:
        print "Wrong~ "
    print rsa_dec(Cipher, prv)

    # Assume that now we capture the ciphertext m.

    # Here we can choose a integer > 1 as S and can not use 2*2*2*2*...

    S = 3
    print "The S I chose is: " + str(S)
    # We can change our captured cipher using S

    # m' = S ^ e % N
    Cipher_mod  = gmpy2.powmod(S, pub[0], pub[1])
    # C' = (C * m') mod N
    Cipher_mod  = gmpy2.f_mod(gmpy2.mul(Cipher, Cipher_mod), pub[1])
    # M' = E(C')
    Message_mod = rsa_dec(Cipher_mod, prv)

    #transform ASCII to int
    Message_num = int(Message_mod.encode('hex'), 16)

    # The most important step :
    Message_num = gmpy2.f_mod(gmpy2.mul(gmpy2.mpz(Message_num), gmpy2.invert(S, pub[1])), pub[1])
    # transform int to ASCII.
    Message     = hex(Message_num).strip('0xXlL')
    if len(Message) % 2 == 1:
        Message = '0' + Message
    print 'The message we recovered: '
    print Message.decode('hex')
    def compute_tuple(self):
        self.PP = self.pick_pp()
        # print("pick PP done")
        self.coefficient_generation()
        # print("coefficient generation done")

        pi1 = gmpy2.f_mod((self.pi + self.a1 * 1), self.PP)
        ppi1 = gmpy2.f_mod((self.ppi + self.aa1 * 1), self.PP)
        qi1 = gmpy2.f_mod((self.qi + self.b1 * 1), self.PP)
        qqi1 = gmpy2.f_mod((self.qqi + self.bb1 * 1), self.PP)
        hi1 = gmpy2.f_mod((self.c0 + self.c1 * 1 + self.c2 * 1 * 1), self.PP)
        hhi1 = gmpy2.f_mod((self.cc0 + self.cc1 * 1 + self.cc2 * 1 * 1),
                           self.PP)

        pi2 = gmpy2.f_mod((self.pi + self.a1 * 2), self.PP)
        ppi2 = gmpy2.f_mod((self.ppi + self.aa1 * 2), self.PP)
        qi2 = gmpy2.f_mod((self.qi + self.b1 * 2), self.PP)
        qqi2 = gmpy2.f_mod((self.qqi + self.bb1 * 2), self.PP)
        hi2 = gmpy2.f_mod((self.c0 + self.c1 * 2 + self.c2 * 2 * 2), self.PP)
        hhi2 = gmpy2.f_mod((self.cc0 + self.cc1 * 2 + self.cc2 * 2 * 2),
                           self.PP)

        pi3 = gmpy2.f_mod((self.pi + self.a1 * 3), self.PP)
        ppi3 = gmpy2.f_mod((self.ppi + self.aa1 * 3), self.PP)
        qi3 = gmpy2.f_mod((self.qi + self.b1 * 3), self.PP)
        qqi3 = gmpy2.f_mod((self.qqi + self.bb1 * 3), self.PP)
        hi3 = gmpy2.f_mod((self.c0 + self.c1 * 3 + self.c2 * 3 * 3), self.PP)
        hhi3 = gmpy2.f_mod((self.cc0 + self.cc1 * 3 + self.cc2 * 3 * 3),
                           self.PP)

        return [[pi1, ppi1, qi1, qqi1, hi1, hhi1],
                [pi2, ppi2, qi2, qqi2, hi2, hhi2],
                [pi3, ppi3, qi3, qqi3, hi3, hhi3]]
Exemplo n.º 47
0
import sys
from gmpy2 import mpz  
from gmpy2 import invert
from gmpy2 import powmod  
from gmpy2 import f_mod
from gmpy2 import mul 
b=2**20 
B=mpz(b)  
p=mpz('13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171')  
g=mpz('11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568')  
h=mpz('3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333')  
g_power_b=powmod(g,B,p)   
hash_table={}  
for x1 in range(B):  
    hash_table[f_mod(mul(h,invert(powmod(g,x1,p),p)),p)]=x1
  
print "Table is completed"  
  
for x0 in range(B):  
    middle_value=powmod(g_power_b,x0,p)  
    if hash_table.has_key(middle_value):    
        print x0  
        x1=hash_table[middle_value]  
        print x1  
        break  
  
x=(x0*B+x1)%(p-1)  
print x
Exemplo n.º 48
0
def calc1(i):
    denominv = pow(g, i, p)
    denom = gmpy2.invert(denominv, p)
    tval = gmpy2.mul(h, denom)
    retval = gmpy2.f_mod(tval, p)
    return retval
Exemplo n.º 49
0
print q3
print "========"

##########################################

c = mpz(22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540)

phi_N1 = mpz(p1-1)*mpz(q1-1)
e = mpz(65537)
d = invert(e,phi_N1)

m = powmod(c,d,N1)
hex_m = ''

while m > 0:
	mod = f_mod(m,16)
	hex_m = str(hex(mod))[2:]+hex_m
	m = (m-mod)/16

hex_m = '0x0'+hex_m
print "========"
print "plain:"
print hex_m
plain_m = '466163746f72696e67206c65747320757320627265616b205253412e'

def hex_2_string(str_i):
        str_o = ""
        i=0
        while i < len(str_i):
                str_o = str_o + chr(int(str_i[i:i+2],16))
                i+=2
Exemplo n.º 50
0
Arquivo: PVSS.py Projeto: dat96le/rng
def findPrime(nbits):
    rs = gmpy2.random_state(gmpy2.f_mod(mpz(time.time()), 60))
    test = mpz(1)
    while not gmpy2.is_prime(test):
        test = gmpy2.mpz_urandomb(rs, nbits - 1) + 2**(nbits - 1)
    return test
Exemplo n.º 51
0
def checkD(e,d,phi):
  if not g.f_mod( g.mul(e,d), phi ) == g.mpz('1'):
    raise Exception("Bad D generated")
Exemplo n.º 52
0
def break_primes(n, process_id, sync, output):
    # check to see if the primes were the same
    gmpy2.get_context().precision = 4096
    n_sqrt = gmpy2.sqrt(n)
    # check to see if the modulo is a perfect square root of itself
    if n_sqrt % 1 == 0.0:
        processLock.acquire()
        if output.empty():
            output.put(n_sqrt)
            sync.set()
            print("Duplicate primes detected! Prime is", n_sqrt)
        processLock.release()
        return n_sqrt

    # trial division
    processLock.acquire()
    # loop through the trivial primes
    for i in range(len(primes)):
        # check if we've haven't found anything yet
        if output.empty():
            # the smaller of any factors of modulo has to be less than the sqrt of that modulo so we can give up if we
            # haven't found anything by then
            if primes[i] > gmpy2.sqrt(n):
                break
            elif gmpy2.f_mod(n, primes[i]) == 0.0:
                # share the result and handle the multiprocessing cleanup
                print("Trial Division Success! Divisible by", primes[i])
                print("Result is", n // primes[i])
                output.put(primes[i])
                sync.set()
                # processLock.release()
                return primes[i]
    processLock.release()
    # informative statements
    if DEBUG:
        print("No Trivial")
        print("nothing easy :(")

    # check to see if the modulo is vulnerable to pollard p - 1
    p1_result = pollard_p1(n, process_id)
    processLock.acquire()
    if p1_result > 1 and output.empty():
        # share the result and handle the multiprocessing cleanup
        print(process_id, "p1 factor found:", p1_result)
        output.put(p1_result)
        sync.set()
        return p1_result
    if DEBUG:
        print(process_id, ": p1 no factors")
    processLock.release()

    # check to see if the modulo is vulnerable to william p + 1
    william = 1  # william_p1(n, process_id)
    processLock.acquire()
    if william > 1 and output.empty():
        # share the result and handle the multiprocessing cleanup
        print("William factor found:", william)
        output.put(william)
        sync.set()
        return william
    if DEBUG:
        print(process_id, ": william no factors")
    processLock.release()

    # if all else fails try pollard rho on it
    rho_result = pollard_rho(n, process_id)
    processLock.acquire()
    if output.empty():
        # share the result and handle the multiprocessing cleanup
        print(process_id, "rho factor found:", rho_result)
        output.put_nowait(rho_result)
        sync.set()
    # processLock.release()
    return rho_result
Exemplo n.º 53
0
 def calcR(self,k,p,q):
    r=gmpy2.f_mod(gmpy2.powmod(g,k,p),q)
    return r
Exemplo n.º 54
0
 def check_delta(self):
     """"Check delta condidtion properly with definition"""
     return f_mod((4 * (self.A * self.A * self.A) + 27 *
                   (self.B * self.B)), self.P) != 0
Exemplo n.º 55
0
 def calcS(self,k,h,x,r):
     s=gmpy2.f_mod(gmpy2.mpz(gmpy2.mul(gmpy2.invert(k,q),gmpy2.add(h,gmpy2.mul(x,r)))),q)
     return s
Exemplo n.º 56
0
def big_num():
    operator = request.values.get('operator')
    result = '1'

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

    x[0] = 56687054115473550533
    x[1] = 71501923691929981066
    x[2] = 1162551557687152936
    x[3] = 88117163952857350660
    x[4] = 16754986973331962115

    t[0] = gmpy2.sub(x[1], x[0])
    t[1] = gmpy2.sub(x[2], x[1])
    t[2] = gmpy2.sub(x[3], x[2])
    t[3] = gmpy2.sub(x[4], x[3])

    u[0] = abs(gmpy2.mul(t[2], t[0]) - gmpy2.square(t[1]))
    u[1] = abs(gmpy2.mul(t[3], t[1]) - gmpy2.square(t[2]))

    # M'
    gcd = gmpy2.gcd(u[0], u[1])

    # true M = M'/2
    M = gmpy2.mpz(gmpy2.div(gcd, 2))

    # x[2] = A * x[1] + B (mod M)
    # x[1] = A * x[0] + B (mod M)
    # ---------------------------
    # x[2] - x[1] = A (x[1] - x[0]) mod M

    # t[1] = A * t[0] mod M
    # A * t[0] = t[1] mod M

    # -x[0] * x[2] = -A * x[0] * x[1] - B * x[0] (mod M)
    #  x[1] * x[1] =  A * x[0] * x[1] + B * x[1] (mod M)
    # --------------------------------------------------
    # x[1]^2 - (x[0] * x[2]) = B (x[1] - x[0]) mod M

    # B * t[0] = (x[1]^2 - (x[0] * x[2])) mod M

    # easier way to solve B:
    # find A first
    # (A * x[0] + B) = x[1] mod M

    # used Diophantine equations to retrieve A and B
    # using M
    #A = 12630192673789351314
    #B = 35234390061212433526

    # using M = M'/2 or M'/3
    A = 12630192673789351314
    B = 35234390061212433526

    print "t[0] = %i\nt[1] = %i\nt[2] = %i\nt[3] = %i\n\nu[0] = %i\nu[1] = %i\n\nM' = gcd(u[0], u[1]) = %i\nM = M'/2 = %i\n" % (
        t[0], t[1], t[2], t[3], u[0], u[1], gcd, M)

    x[5] = gmpy2.mpz(
        gmpy2.f_mod(gmpy2.add(gmpy2.mul(A, x[4]), gmpy2.mpz(B)), gmpy2.mpz(M)))
    x[6] = gmpy2.mpz(
        gmpy2.f_mod(gmpy2.add(gmpy2.mul(A, x[5]), gmpy2.mpz(B)), gmpy2.mpz(M)))
    x[7] = gmpy2.mpz(
        gmpy2.f_mod(gmpy2.add(gmpy2.mul(A, x[6]), gmpy2.mpz(B)), gmpy2.mpz(M)))
    x[8] = gmpy2.mpz(
        gmpy2.f_mod(gmpy2.add(gmpy2.mul(A, x[7]), gmpy2.mpz(B)), gmpy2.mpz(M)))
    x[9] = gmpy2.mpz(
        gmpy2.f_mod(gmpy2.add(gmpy2.mul(A, x[8]), gmpy2.mpz(B)), gmpy2.mpz(M)))
    x[10] = gmpy2.mpz(
        gmpy2.f_mod(gmpy2.add(gmpy2.mul(A, x[9]), gmpy2.mpz(B)), gmpy2.mpz(M)))
    x[11] = gmpy2.mpz(
        gmpy2.f_mod(gmpy2.add(gmpy2.mul(A, x[10]), gmpy2.mpz(B)),
                    gmpy2.mpz(M)))

    #print "x[5] = ", x[5]
    #print "x[6] = ", x[6]
    #print "x[7] = ", x[7]
    #print "x[8] = ", x[8]
    #print "x[9] = ", x[9]
    print "x[10] = ", x[10]
    print "x[11] = ", x[11]

    print "A     = ", A
    print "B     = ", B

    return