コード例 #1
0
ファイル: system.py プロジェクト: pelekoudasq/core
    def _dsa_verify(self, exponent, signature, public_key):
        """
        Verifies that the provided DSA-signature `signature` signs the given
        `exponent` under the given `public_key`

        :type exponent: mpz
        :type signature: dict
        :type public_key: ModPrimeElement
        :rtype: bool
        """
        __group = self.__group
        __q = self.__order

        _, c_1, c_2 = self.extract_dsa_signature(signature)

        # Commitments' validity check
        for c in (c_1, c_2):
            if not 0 < c < __q:
                return False

        # Proceed to signature validation

        c_2_inv = invert(c_2, __q)                                      # c_2 ^ -1 modq

        v_1 = mul(exponent, c_2_inv) % __q                              # (e + c_2 ^ -1) modq
        v_2 = mul(c_1, c_2_inv) % __q                                   # (v_1 * c_2 ^ -1) modq

        element = (__group.generate(v_1) * public_key ** v_2).value     # (g ^ v_1 * y ^ v_2) modp

        # ((g ^ v_1 * y ^ v_2) modp) modq == c_1 ?
        return element % __q == c_1
コード例 #2
0
ファイル: mutil.py プロジェクト: joseph8th/mandelbrat
def mlmul(u, v):
    """ Multi-library multiplication function. """

    if u.mp_t != v.mp_t:
        return None

    if u.mp_t == 'bigfloat':

        from bigfloat import BigFloat, mul

        z_real = mul(u.mp_c.real, v.mp_c.real) - \
                 mul(u.mp_c.imag, v.mp_c.imag)

        z_imag = mul(u.mp_c.real, v.mp_c.imag) + \
                 mul(u.mp_c.imag, v.mp_c.real)

        z = Arguments({'real': z_real, 'imag': z_imag})

    else:

        from mpmath import fmul

        z = fmul(u.mp_c, v.mp_c)
    
    return MultiLibMPC(z.real, z.imag, u.mp_t, u.prec)
コード例 #3
0
ファイル: base-dsa.py プロジェクト: ohmygodlin/snippet
def sameR():
    f3 = open(r"packet3/message3", 'r')
    f4 = open(r"packet4/message4", 'r')
    data3 = f3.read()
    data4 = f4.read()
    sha = sha1()
    sha.update(data3)
    m3 = int(sha.hexdigest(), 16)
    sha = sha1()
    sha.update(data4)
    m4 = int(sha.hexdigest(), 16)
    print m3, m4
    s3 = 0x1B474F2C1C9E85B72841AD84D9A871A11EF0F323
    s4 = 0x0EA21858C18AA1EDF4058B6EB9E02B0176243658
    r = 0x12E780EE8471DC3552572BB6E818F6D22CE16EA4
    #k(s1-s2) = H(m1)-H(m2) mod q
    ds = s4 - s3
    dm = m4 - m3
    k = gmpy2.mul(dm, gmpy2.invert(ds, q))
    k = gmpy2.f_mod(k, q)
    #x = r^(-1) * (ks-H(m)) mod q
    tmp = gmpy2.mul(k, s3) - m3
    x = tmp * gmpy2.invert(r, q)
    x = gmpy2.f_mod(x, q)
    print hex(x)
コード例 #4
0
 def compute_N(self, Ni_list):
     L1 = mpz(int((0 - 2) * (0 - 3) / ((1 - 2) * (1 - 3))))
     L2 = mpz(int((0 - 1) * (0 - 3) / ((2 - 1) * (2 - 3))))
     L3 = mpz(int((0 - 1) * (0 - 2) / ((3 - 1) * (3 - 2))))
     self.N = gmpy2.f_mod(gmpy2.mul(Ni_list[0], L1) + gmpy2.mul(Ni_list[1], L2) + gmpy2.mul(Ni_list[2], L3), self.PP)
     # print("Ni_list = ", Ni_list)
     print("Candidate modulus = ", self.N)
コード例 #5
0
    def decrypt(self, common_pk, sk, vec, ct, max_inner_prod):
        assert len(ct['ct_dict']) == len(sk['d'])

        p = gp.mpz(common_pk['p'])
        g = gp.mpz(common_pk['g'])
        z = gp.mpz(sk['z'])
        d = sk['d']

        vec_parties = self._split_vector(vec, ct['parties'])
        ct_dict = ct['ct_dict']

        g_f = gp.mpz(1)
        for idx in ct_dict.keys():
            vec_idx = vec_parties[idx]
            c_idx = ct_dict[idx]['c']
            t_idx = ct_dict[idx]['t']
            d_idx = d[idx]

            assert len(vec_idx) == len(c_idx)
            init_idx = gp.mpz(1)
            for j in range(len(c_idx)):
                init_idx = gp.mul(
                    init_idx, gp.powmod(gp.mpz(c_idx[j]), gp.mpz(vec_idx[j]),
                                        p))

            g_f = gp.mul(
                g_f,
                gp.divm(init_idx, gp.powmod(gp.mpz(t_idx), gp.mpz(d_idx), p),
                        p))
        g_f = gp.divm(g_f, gp.powmod(g, z, p), p)

        f = self._solve_dlog(p, g, g_f, max_inner_prod)
        return f
コード例 #6
0
ファイル: breakRSA.py プロジェクト: varren/Cryptography
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
コード例 #7
0
ファイル: week6.py プロジェクト: jiulongw/coursera
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))
コード例 #8
0
ファイル: dlog.py プロジェクト: Tassia1900/coursera-crypto
def main():
    start = time.clock()
    B = 2**20
    x1 = 0
    x0 = 0
    g_reverse = mpz(reverse(g,p)) #g**-1
    g_B = mpz(pow(g,B,p))         #(g**B) mod p

    #Iterazio bakoitzean berreketa guztia kalkulatu beharrean,
    #aurreko iterazioko balioari berreketaren oinarria bidertu
    # x**3 = (x**2)*x; x**4 = (x**3)*x ...
    next_value = h                #x1=0 => h/g**x1=h/1=h
    try:
        for x1 in xrange(B):
	    #Lortu h/g**x1 eta gorde hiztegian
	    hashTable[next_value] = x1
	    #next_value = h/g**(x1 + 1) = h/(g**x1)*g:
            next_value = mpz(mul(next_value,g_reverse)%p)
        print 'Hiztegia amaitu da: ' + str(time.clock() - start)
	next_value = 1                #x0=0 => (g**B)**x0=1
        for x0 in xrange(B):
	    #Lortu (g**B)**x0 eta bilatu hiztegian
	    if hashTable.has_key(next_value):
		print 'Emaitza aurkitu da: ' + str(time.clock() - start)
		print '   x0 = ' + str(x0)
		print '   x1 = ' + str(hashTable[next_value])
		print '   x = ' + str(mpz(addmul(mpz(hashTable[next_value]),mpz(x0),mpz(B))%p)) 
		sys.exit()
	    next_value = mpz(mul(next_value,g_B)%p)
    except KeyboardInterrupt:
        print 'Keyboard interrupt: x1=' + str(x1) + ', x0=' + str(x0)
        print 'Denbora: ' + str(time.clock() - start)
        sys.exit() 
コード例 #9
0
ファイル: paillier.py プロジェクト: egrinstein/paillier
    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))
コード例 #10
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
コード例 #11
0
ファイル: repos.py プロジェクト: 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
コード例 #12
0
def factoring_challenge_3():
    """
    Given |3p - 2q| < N^(1/4) and considering A = (3p + 2q) / 2 we can show that
    A - sqrt(6N) < 1 => A = ceil(sqrt(6N)).
    Let x be equal distance from A to 3p and 2q, then x = sqrt(A^2 - 6N)
    => we can calculate p and q based on this.
    """
    modulus = mpz(
        "72006226374735042527956443552558373833808445147399984182665305798191"
        "63556901883377904234086641876639384851752649940178970835240791356868"
        "77441155132015188279331812309091996246361896836573643119174094961348"
        "52463970788523879939683923036467667022162701835329944324119217381272"
        "9276147530748597302192751375739387929"
    )
    a, rem = gmpy2.isqrt_rem(6 * modulus)
    if rem > 0:
        a += 1
    x = gmpy2.isqrt(a ** 2 - 6 * modulus)
    a_minus_x, a_plus_x = a - x, a + x

    # either p = (A - x) / 3 and q = (A + x) / 2
    p, rem = gmpy2.f_divmod(a_minus_x, 3)
    if rem == 0:
        q, rem = gmpy2.f_divmod(a_plus_x, 2)
        if gmpy2.mul(p, q) == modulus:
            return p if p < q else q

    # or p = (A + x) / 3 and q = (A - x) / 2
    p, rem = gmpy2.f_divmod(a_plus_x, 3)
    if rem == 0:
        q = gmpy2.f_div(a_minus_x, 2)
        if gmpy2.mul(p, q) == modulus:
            return p if p < q else q
コード例 #13
0
ファイル: challenge 4.py プロジェクト: roydenezra/Udacity
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
コード例 #14
0
def factor_prime(prime):

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

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

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

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

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

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

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

    return
コード例 #15
0
ファイル: system.py プロジェクト: pelekoudasq/core
    def _dsa_signature(self, exponent, private_key):
        """
        Returns and computes the DSA-signature

                {
                    'exponent': e,
                    'commitments': {
                        'c_1': (g ^ r modp) modq
                        'c_2': (e + x * c_1)/r modq
                    }
                }

        of the provided `exponent` e (assumed to be in the range {1, ..., q - 1})
        under the `private_key` x for a once used randmoness 1 < r < q

        :type exponent: mpz
        :type private_key: mpz
        :rtype: dict
        """
        __group = self.__group
        __q = self.__order

        randomness = __group.random_exponent()                           # 1 < r < q
        c_1 = __group.generate(randomness).value % __q                   # (g ^ r modp) modq

        exps = __group.add_exponents(exponent, mul(private_key, c_1))    # (e + x * c_1) modq
        r_inv = invert(randomness, __q)                                  # r ^ -1 modq
        c_2 = mul(exps, r_inv) % __q                                     # (e + x * c_1)/r modq

        signature = self.set_dsa_signature(exponent, c_1, c_2)
        return signature
コード例 #16
0
ファイル: api.py プロジェクト: Captaincheq/tools
def rsa():

    p = gmpy2.mpz(int(request.values.get('p')))
    # print(p)
    q = gmpy2.mpz(int(request.values.get('q')))
    e = gmpy2.mpz(int(request.values.get('e')))
    operator = request.values.get('operator')
    try:
        if p and q and e and operator:
            if not gmpy2.is_prime(p) or not gmpy2.is_prime(q):
                resu = {'code': 9999, 'message': 'p和q必须是素数'}
                return json.dumps(resu, ensure_ascii=False)
            n = gmpy2.mul(p, q)
            if operator == 'decode':
                c = gmpy2.mpz(int(request.values.get('c')))
                phi_n = gmpy2.mul(gmpy2.sub(p, 1), gmpy2.sub(q, 1))
                d = gmpy2.invert(e, phi_n)  # private key
                m = gmpy2.powmod(c, d, n)
                print(m)
                print(d)
                resu = {'code': 200, 'm': str(m), 'd': str(d)}
                return json.dumps(resu, ensure_ascii=False)
            elif operator == 'encode':
                m = gmpy2.mpz(int(request.values.get('m')))
                c = gmpy2.powmod(m, e, n)
                resu = {'code': 201, 'c': str(c)}
                return json.dumps(resu, ensure_ascii=False)
        else:
            resu = {'code': 10001, 'message': '参数不能为空!'}
            return json.dumps(resu, ensure_ascii=False)
    except:
        resu = {'code': 10002, 'message': '异常。'}
        return json.dumps(resu, ensure_ascii=False)
コード例 #17
0
ファイル: test_ks.py プロジェクト: deepakkapoor624/Projects
    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
コード例 #18
0
ファイル: test_ks.py プロジェクト: sqf-ice/VerilogCodeECC
    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
コード例 #19
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
コード例 #20
0
ファイル: repos.py プロジェクト: 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
コード例 #21
0
ファイル: test_ks.py プロジェクト: deepakkapoor624/Projects
    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
コード例 #22
0
ファイル: factoringRSA.py プロジェクト: jebusfx/cryptoutils
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)
コード例 #23
0
ファイル: test_ks.py プロジェクト: sqf-ice/VerilogCodeECC
    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
コード例 #24
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)
コード例 #25
0
ファイル: test_factoring.py プロジェクト: redcat34/crypto
 def test_factors2(self):
     p = gmpy2.mpz('776531419')
     q = gmpy2.mpz('776531479')
     n = gmpy2.mul(p, q)
     factor = factoring.Factoring(n)
     pc, qc = factor.calc_near()
     self.assertEquals(p, pc)
     self.assertEquals(q, qc)
     self.assertEquals(n, gmpy2.mul(pc, qc))
コード例 #26
0
ファイル: gmpy_math.py プロジェクト: tongdun/iBond-flex
def crt(mp, mq, p, q, q_inverse, n):
    """the Chinese Remainder Theorem as needed for decryption.
       return the solution modulo n=pq.
   """
    # u = (mp - mq) * self.q_inverse % self.p
    # x = (mq + (u * self.q)) % self.public_key.n

    u = gmpy2.mul(mp-mq, q_inverse) % p
    x = (mq + gmpy2.mul(u, q)) % n
    return int(x)
コード例 #27
0
ファイル: factoringRSA.py プロジェクト: jebusfx/cryptoutils
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
コード例 #28
0
ファイル: hw5.py プロジェクト: bailan0506/Cryptography-I
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)
コード例 #29
0
ファイル: dlog.py プロジェクト: redcat34/crypto
 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)
コード例 #30
0
ファイル: factoringRSA.py プロジェクト: jebusfx/cryptoutils
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
コード例 #31
0
ファイル: dlog.py プロジェクト: RinSer/crypto
def mit_in_the_middle(h, g, p, B):
    tab = hash_table(h, g, p, B)
    for x in range(B - 1):
        val = gmpy2.powmod(g, gmpy2.mul(B, x), p)
        if val in tab:
            # print val
            x0 = x
            x1 = tab[val]
            # print x0, x1

    return gmpy2.mul(x0, B) + x1
コード例 #32
0
ファイル: dc.py プロジェクト: mbiokyle29/crypto
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
コード例 #33
0
ファイル: factoringRSA.py プロジェクト: jebusfx/cryptoutils
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)
コード例 #34
0
ファイル: verify_cc.py プロジェクト: nimocat/double-SSS-mpc
 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
コード例 #35
0
def rptsq(base, toraise):
    #repeated squaring algo
    #base = value to raise, toraise = exponent
    binstr = bin(toraise)[2:] #string in binary of toraise
    curmult = base
    curval = mpz('1')
    for digit in reversed(xrange(len(binstr))):
            if binstr[digit] == '1':
                curval = gmpy2.mul(curval, curmult)
            curmult = gmpy2.mul(curmult, base)
    return curval
コード例 #36
0
ファイル: factoringRSA.py プロジェクト: jebusfx/cryptoutils
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
コード例 #37
0
ファイル: mutil.py プロジェクト: joseph8th/mandelbrat
def mandelfun(c, z0, e, n):
    """ 
    Provides methods used to compute multi-privkey key types.
    Takes mpc objects as parameters. 
    """
        
    z = z0
    while n > 0:
        z = mul(z, mul(e, mul(c, c)))
        n -= 1

    return z
コード例 #38
0
ファイル: polynomial.py プロジェクト: crazytan/seclogin
def get_lambda_i(x, i):
    lambda_i = mpz(1)
    for j in xrange(len(x)):
        if i != j:
            if x[i] == x[j] and __debug__:
                print x
                print i
                print j
                print config.q
            tmp = gmpy2.invert(gmpy2.sub(x[j], x[i]), config.q)
            tmp = gmpy2.t_mod(gmpy2.mul(x[j], tmp), config.q)
            lambda_i = gmpy2.t_mod(gmpy2.mul(lambda_i, tmp), config.q)
    return lambda_i
コード例 #39
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)
コード例 #40
0
ファイル: factoringRSA.py プロジェクト: jebusfx/cryptoutils
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
コード例 #41
0
ファイル: breakRSA.py プロジェクト: varren/Cryptography
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
コード例 #42
0
ファイル: number.py プロジェクト: cowboysmall/crypto
def factorize(number, delta):
    for i in xrange(1, delta + 1):
        square_root     = isqrt(number)
        average         = square_root + i
        average_squared = mul(average, average)

        x = isqrt(average_squared - number)
        p = (average - x)
        q = (average + x)

        if mul(p, q) == number:
            return (p, q, i)

    return (0, 0, 0)
コード例 #43
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)
コード例 #44
0
ファイル: key_distribution.py プロジェクト: bailan0506/p2psp
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)
コード例 #45
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)
コード例 #46
0
def rsa_recovery(dp, dq, ciphertext, keysize=1024, start=3):
    '''
    This extensive process loops through all unknown e, typically between 3..65537
    and given the dP and dQ will search for primes p and q, then attempt to
    decrypt the ciphertext that is known to have been encrypted with them.
    '''
    # init counters
    r, p, q, d, count, count2, count3 = (0L, 0L, 0L, 0L, 0, 0, 0) 
    # start generalised loop for an unknown e
    for j in range(start, 65538, 2):
        dp1 = long(gmpy2.mul(dp, j) - 1)
        for k in range(3, j):
            d = long(k)
            a, r = gmpy2.t_divmod(dp1, d)
            assert(dp1 == (k * a) + r)
            if r == 0:
                count += 1
                p = long(a + 1)
                if gmpy2.is_odd(p) and gmpy2.is_strong_prp(p, 10):
                    count2 += 1
                    dq1 = long(gmpy2.mul(dq, j) - 1)
                    for l in range(3, j):
                        d = long(l)
                        a, r = gmpy2.t_divmod(dq1, d)
                        assert(dq1 == (l * a) + r)
                        if r == 0:
                            q = long(a + 1)
                            if gmpy2.is_odd(q) and gmpy2.is_strong_prp(q, 10):
                                count3 += 1
                                # just some basic progress on the console
                                if count3 % 10 == 0:
                                    sys.stdout.write('.')
                                    sys.stdout.flush()
                                # only attempt the decrypt if p,q are expected bitlength
                                if p.bit_length() + q.bit_length() == keysize:
                                    try:
                                        result = rsa_decrypt(p, q, ciphertext, j)
                                        if len(result) == 0 or result == "None":
                                            # indicates a failed decryption attempt
                                            sys.stdout.write('x')
                                        else:
                                            # SUCCESS! This is your decrypted message, sir...
                                            print "\n:: DECRYPTED::\n message = %s" % result
                                        # show all the p, q candidates just in case
                                        print "\np = %X\nq = %X\n" % (p, q)
                                    except Exception as e:
                                        print "ERROR: ", e # if cipher text length wrong, change decryption padding etc.
                                        pass # do nothing
    # finish with a counter summary
    print "count: %d  count2: %d  count3: %d\n\n" % (count, count2, count3)
コード例 #47
0
ファイル: rsa-factors.py プロジェクト: alejandroclaro/courses
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)
コード例 #48
0
def invHessian(x, y, t_1, t_2):
    hess = hessian(x, y, t_1, t_2)
    a = mpfr(hess[0][0])
    b = mpfr(hess[0][1])
    c = mpfr(hess[1][0])
    d = mpfr(hess[1][1])
    det = mpfr(a * d - b * c)
    H_inv = np.ones((2, 2), dtype=object)
    q = (mpfr(1.0) / det)
    H_inv[0][0] = gmpy2.mul(q, d)
    H_inv[0][1] = gmpy2.mul(-q, b)
    H_inv[1][0] = gmpy2.mul(-q, c)
    H_inv[1][1] = gmpy2.mul(q, a)
    return H_inv
コード例 #49
0
def check_sterbenz_apply(interval1, interval2):
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundDown,
                             precision=mpfr_proxy_precision) as ctx:
        two_y_left = gmpy2.mul(mpfr("2.0"), mpfr(interval2.lower))
        two_x_left = gmpy2.mul(mpfr("2.0"), mpfr(interval1.lower))
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundUp,
                             precision=mpfr_proxy_precision) as ctx:
        y_right = mpfr(interval2.upper)
        x_right = mpfr(interval1.upper)
    if x_right <= two_y_left and y_right <= two_x_left:
        return True
    return False
コード例 #50
0
ファイル: key_distribution.py プロジェクト: bailan0506/p2psp
def generate_key_r(bits,x):
    """ Generate the key r. 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, includes x_i which has been distributed members.         
    """

    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)
    
    L=1
    for x_i in x :
       L=gmpy2.mul(L,x_i)
       
    u=gmpy2.invert(delta,L)
    
    """ Because the primes generated are pseudo primes that has passed probable 
        prime test, it is possible that the member cannot calculat the right key.
        Verify the members can calculate the key rightly.
    """
    
    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)
        
        L=1
        for x_i in x :
           L=gmpy2.mul(L,x_i)
           
        u=gmpy2.invert(delta,L)
        
        
    return (g,m,u,L,r)
コード例 #51
0
ファイル: mqv.py プロジェクト: 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
コード例 #52
0
def main():
    if not (sys.argv[1] == "-i"):
        print("Invalid usage! rsa_mitm_attack_117516.py -i <filename>")
        quit()
    print("reading in values")
    lines = [line.rstrip('\n') for line in open(sys.argv[2])]
    n = mpz(lines[2])
    e = int(lines[4])
    C = mpz(lines[6])
    b = int(lines[8])
    S = int(b)
    T = int(b)
    print("starting dict creation")
    found = False
    dict = {}

    if (S * T) < b:
        print("S * T is too small")
        print(S * T)
        quit()
    for s in range(1, S, 1):
        Cs = fmod(mul(C, (powmod(powmod(s, e, n), -1, n))), n)
        dict[Cs] = s
    print("finished dict creation")
    print("starting comparision")
    for t in range(1, T, 1):
        key = powmod(t, e, n)
        if key in dict:
            print("Found collision at s = " + str(dict[key]) + " and t = " +
                  str(t) + ", both equal " + str(key))
            print("X = " + str(s * t))
            found = True

    if not found:
        print("No collision found")
 def encrypt(self, massage):
     random = self.gen_coprime(self.N)
     ciphertext = gmpy2.f_mod(
         gmpy2.mul(gmpy2.powmod(self.generator, massage, self.N * self.N),
                   gmpy2.powmod(random, self.N, self.N * self.N)),
         self.N * self.N)
     return ciphertext
コード例 #54
0
ファイル: dlog.py プロジェクト: RinSer/crypto
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
コード例 #55
0
ファイル: tree_model.py プロジェクト: soarlab/paf
 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))
コード例 #56
0
ファイル: bruteSmall.py プロジェクト: chrisjleaf/cryptopals
def breakKey(N,e):
  P,Q = bruteSmall(N)

  phi = g.mul( g.sub(P,1), g.sub(Q,1) ) 
  D = g.invert(e,phi)
  checkD(e,D,phi)
  return (P,Q,D)
コード例 #57
0
ファイル: bruteSmall.py プロジェクト: chrisjleaf/cryptopals
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
コード例 #58
0
ファイル: factorize.py プロジェクト: cowboysmall/crypto
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
コード例 #59
0
ファイル: ex6.py プロジェクト: maximbu/coursera
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]