Esempio n. 1
1
def many():
  for n in range(3, 10000, 2):
    ft = flt(n)
    if ft != bool(gmpy.is_prime(n)):
      print "FT", ft, n

    bt = b2spp(n)
    if bt != bool(gmpy.is_prime(n)):
      print "BT", bt, n

    """
Esempio n. 2
1
File: q37.py Progetto: mwcz/euler
def truncatable(_s):

    s = str(_s)
    l = len(s)

    for i in range(l):
        if not is_prime(int(s[i:])):
            return False
        if not is_prime(int(s[: i + 1])):
            return False

    return True
def gen_safe_prime(BIT_LEN):
    found=False
    while found==False:
        q=random.randrange(2**(BIT_LEN-2),2**(BIT_LEN-1))
        p=2*q+1
        found=gmpy.is_prime(p) and gmpy.is_prime(q)
    return p
Esempio n. 4
0
def generate_amicable_pair(n, m, limit):
    '''
    Genereate amicable pair by Euler's rule
    http://en.wikipedia.org/wiki/Euler's_rule
    '''
    
    lst = []
    if (n <= m):
        n += 1
        m = 1
    print n
    print m
    #Check n < sqrt(max potential amicable number) because max checked number is 10000
    while n < limit**0.5:
        while m < n:
            p = (2**(n - m) + 1) * 2**m - 1
            q = (2**(n - m) + 1) * 2**n - 1
            r = (2**(n - m) + 1)**2 * 2**(m + n) - 1
            pair = []
            print n
            print m
            print p * q * 2**n
            print r * 2**n
            #Test
            if is_prime(p) and is_prime(q) and is_prime(r):
                pair.append(p * q * 2**n)
                pair.append(r * 2**n)
                lst.append(pair)
                lst.append(n)
                lst.append(m)
                return lst
            m += 1
        n += 1
        m = 1
    return None
Esempio n. 5
0
def main(cert_path, data_path, offset):
  mod = get_modulus(cert_path)
  mod = gmpy.mpz(mod, 16)
  key_size = int(mod.bit_length() / 16)
  offset = int(offset, 16)
  print('Prime should be at offset: %x'%offset)
  print('Key size: %d\n'%key_size)
  with open(data_path, 'rb') as f:
    mm_data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

    print('Hexdump of surrounding data:')
    hexdump(mm_data, max(0, offset - 1024), 2048)
    p = gmpy.mpz(long(mm_data, offset, key_size))
    if gmpy.is_prime(p) and p != mod and mod % p == 0:
      print('Prime factor found: %s\n'%p)
      hexbytes = binascii.hexlify(mm_data[offset:offset+key_size]).decode('ascii').upper()
      hexbytes = re.sub(r'(..)', r'\x\1', hexbytes)
      print('Prime in greppable ascii: %s\n'%hexbytes)
      p = gmpy.mpz(p)
      e = gmpy.mpz(65537)
      q = gmpy.divexact(mod, p)
      
      assert(gmpy.is_prime(q))

      phi = (p-1) * (q-1)
      d = gmpy.invert(e, phi)
      dp = d % (p - 1)
      dq = d % (q - 1)
      qinv = gmpy.invert(q, p)
      seq = Sequence()
      for x in [0, mod, e, d, p, q, dp, dq, qinv]:
        seq.setComponentByPosition (len (seq), Integer (x))
      print("\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n"%base64.encodestring(encoder.encode(seq)).decode('ascii'))
    else:
      print('Prime factor not found')
def gen_safe_prime(BIT_LEN):
    found = False
    while found == False:
        q = random.randrange(2**(BIT_LEN - 2), 2**(BIT_LEN - 1))
        p = 2 * q + 1
        found = gmpy.is_prime(p) and gmpy.is_prime(q)
    return p
Esempio n. 7
0
def many():
    for n in range(3, 10000, 2):
        ft = flt(n)
        if ft != bool(gmpy.is_prime(n)):
            print "FT", ft, n

        bt = b2spp(n)
        if bt != bool(gmpy.is_prime(n)):
            print "BT", bt, n
        """
Esempio n. 8
0
def factor(x):
    if is_prime(x):
        yield x
    else:
        for prime in (p for p in itertools.count(2) if is_prime(p)):
            if prime > x**0.5 + 1:
                return
            if x % prime == 0:
                for divisor in factor(x / prime):
                    yield divisor
                yield prime
                return
Esempio n. 9
0
 def _test_gp(self, gp, bits):
     q = (gp.p - 1) / 2
     self.assertTrue(gmpy.is_prime(gp.p))
     self.assertTrue(gmpy.is_prime(q))
     self.assertTrue(2 ** (bits - 1) < gp.p)
     self.assertTrue(gp.p < 2 ** bits)
     self.assertTrue(gp.g < gp.p)
     self.assertTrue(3 < gp.g)
     self.assertNotEqual(pow(gp.g, 2, gp.p), 1)
     self.assertNotEqual(pow(gp.g, q, gp.p), 1)
     self.assertNotEqual(divmod(gp.p, gp.g)[1], 0)
     ginv = gmpy.invert(gp.g, gp.p)
     self.assertNotEqual(divmod(gp.p - 1, ginv)[1], 0)
Esempio n. 10
0
 def _test_gp(self, gp, bits):
     q = (gp.p - 1) / 2
     self.assertTrue(gmpy.is_prime(gp.p))
     self.assertTrue(gmpy.is_prime(q))
     self.assertTrue(2**(bits - 1) < gp.p)
     self.assertTrue(gp.p < 2**bits)
     self.assertTrue(gp.g < gp.p)
     self.assertTrue(3 < gp.g)
     self.assertNotEqual(pow(gp.g, 2, gp.p), 1)
     self.assertNotEqual(pow(gp.g, q, gp.p), 1)
     self.assertNotEqual(divmod(gp.p, gp.g)[1], 0)
     ginv = gmpy.invert(gp.g, gp.p)
     self.assertNotEqual(divmod(gp.p - 1, ginv)[1], 0)
Esempio n. 11
0
def find1(N, A=None):
    if A == None:
        A = gmpy.mpz(gmpy.sqrt(N) + 1)
    k = A * A - N
    assert gmpy.is_power(k)
    x = gmpy.sqrt(A * A - N)
    p, q = A - x, A + x
    #print p
    #print q
    assert gmpy.is_prime(p)
    assert gmpy.is_prime(q)
    assert p * q == N
    return p, q
Esempio n. 12
0
def find1(N, A = None):
    if A == None:
        A = gmpy.mpz(gmpy.sqrt(N)+1)
    k = A*A - N
    assert gmpy.is_power(k)
    x = gmpy.sqrt(A*A - N)
    p, q =  A - x, A + x
    #print p
    #print q
    assert gmpy.is_prime(p)
    assert gmpy.is_prime(q)
    assert p*q==N
    return p, q
Esempio n. 13
0
def rsa(c, n, e, p, q=None):
    if q == None:
        q = n / p
        assert gmpy.is_prime(p) and gmpy.is_prime(q)
    f = n - p - q + 1
    g, d, y = xgcd(e, f)
    if d <= 0:
        d = d + f
    print g, d * e % f
    pt = powmod(c, d, n)
    bpt = convert_to_bits(pt, 1024)
    hpt = bits_to_hex(bpt)
    #print hpt
    #print len(hex(pt))
    return pt, ''.join([str(i) for i in bpt])
Esempio n. 14
0
def rsa(c, n, e, p, q=None):
    if q == None:
        q = n/p
        assert gmpy.is_prime(p) and gmpy.is_prime(q)
    f = n - p - q + 1
    g, d, y = xgcd(e, f)
    if d <= 0:
        d = d+f
    print g, d*e % f
    pt = powmod(c, d, n)
    bpt = convert_to_bits(pt, 1024)
    hpt = bits_to_hex(bpt)
    #print hpt
    #print len(hex(pt))
    return pt, ''.join([str(i) for i in bpt])
Esempio n. 15
0
def generate_safe_prime(nbits):
    """ Finds a safe prime of nbits using probabilistic method rather than deterministic;
    because a large prime number is required. """
    q = number.getRandomNBitInteger(nbits)
    while not gmpy.is_prime(q):
        q = gmpy.next_prime(q)
    return int(q)
Esempio n. 16
0
def primenumgen(n):
    p=['+',randnumgen(n)]
    temp=getnum(p)
    if(gmpy.is_prime(gmpy.mpz(temp))>0):
        return getarr(temp)
    else:
        return primenumgen(n)
Esempio n. 17
0
def gen_prime(BITS):
    lb = 2 ** (BITS - 1)
    ub = (2 * lb)
    p = random.randrange(lb,ub)
    while gmpy.is_prime(p) == False:
        p = random.randrange(lb,ub)
        return p
Esempio n. 18
0
def factorize(x=c):
    r'''
    (Takes about 25ms, on c, on a first-generation Macbook Pro)
    >>> factorize(a)
    [3, 41]
    >>> factorize(b)
    [2, 2, 2, 3, 19]
    >>>
    '''
    import gmpy as _g
    savex = x
    prime = 2
    x = _g.mpz(x)
    factors = []
    while x >= prime:
        newx, mult = x.remove(prime)
        if mult:
            factors.extend([int(prime)] * mult)
            x = newx
        prime = _g.next_prime(prime)
    for factor in factors:
        assert _g.is_prime(factor)
    from operator import mul
    assert reduce(mul, factors) == savex
    return factors
Esempio n. 19
0
def main(cert_path, data_path, offset):
    mod = get_modulus(cert_path)
    mod = int(mod, 16)
    key_size = int(mod.bit_length() / 16)
    offset = int(offset, 16)
    print('Prime should be at offset: %x' % offset)
    print('Key size: %d\n' % key_size)
    with open(data_path, 'rb') as f:
        data = f.read()
    print('Hexdump of surrounding data:')
    hexdump(data, max(0, offset - 1024), 2048)
    p = long(data, offset, key_size)
    if gmpy.is_prime(p) and p != mod and mod % p == 0:
        print('Prime factor found: %s\n' % p)
        hexbytes = binascii.hexlify(data[offset:offset +
                                         key_size]).decode('ascii').upper()
        hexbytes = re.sub(r'(..)', r'\x\1', hexbytes)
        print('Prime in greppable ascii: %s\n' % hexbytes)
        p = gmpy.mpz(p)
        e = gmpy.mpz(65537)
        q = gmpy.divexact(mod, p)
        phi = (p - 1) * (q - 1)
        d = gmpy.invert(e, phi)
        dp = d % (p - 1)
        dq = d % (q - 1)
        qinv = gmpy.invert(q, p)
        seq = Sequence()
        for x in [0, mod, e, d, p, q, dp, dq, qinv]:
            seq.setComponentByPosition(len(seq), Integer(x))
        print(
            "\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n"
            % base64.encodestring(encoder.encode(seq)).decode('ascii'))
    else:
        print('Prime factor not found')
Esempio n. 20
0
def sq(q):
    assert is_prime(q)
    p = 2
    while True:
        if p != q:
            yield p * p * q * q * q
        p = int(next_prime(p))
Esempio n. 21
0
def get_seq():
    for i in range(100):
        p = f(f(i)) + 1
        if gmpy.is_prime(p) == 2:
            yield p
        else:
            yield 0
Esempio n. 22
0
 def __init__(self, p=None, q=None, n=None, d=None, e=DEFAULT_EXP):
     """
     Initialize RSA instance using primes (p, q)
     or modulus and private exponent (n, d)
     """
     self.e = e
     if p and q:
         assert gmpy.is_prime(p), 'p is not prime'
         assert gmpy.is_prime(q), 'q is not prime'
         self.p = p
         self.q = q
     elif n and d:
         self.p, self.q = factor_modulus(n, d, e)
     else:
         raise ArgumentError('Either (p, q) or (n, d) must be provided')
     self._calc_values()
Esempio n. 23
0
def testLinearSystem(nbClients, maxexp=16, printing=False):
    assert not gmpy.is_prime(nbClients) is True
    cList = []
    for i in range(0, nbClients):
        cl = LS.LinearSystemPPATSClient(ppatspk, str(i))
        cList.append(cl)
    LSworker = LS.LinearSystemPPATSWorker(ppatspk, ppatssk, clientsList=cList)
    LSworker.makeCircuit()
    LSworker.fillInputGates(maxexp)
    if printing: print 'inputs received by worker'
    L = LSworker.decryptAndCheckProofs(printing)
    if printing: print 'inputs decrypted and proofs checked by worker'
    LSworker.recomInputs()
    if printing: print 'inputs recommited by worker'
    assert L == []
    LSworker.solveSystem(B=None, printing=printing)
    if printing: print 'Linear system solved by worker and proofs prepared'
    ldict = {
        'inputs':
        ('ciphertext', 'message', 'opening', 'openingclear', 'consist'),
        'outputs': ('ciphertext', 'consist'),
        'rest': ('ciphertext', 'consist', 'message', 'opening', 'openingclear')
    }
    newcirc = LSworker.circuit.copy()
    newcirc.removeLevels(ldict)
    LSworker.sendCircuit(newcirc)
    cl0 = LSworker.clientsList[0]
    L = cl0.checkLSCircuitProofs(printing)
    assert L == []
    if printing: print 'Solution of the linear System is:\n', LSworker.Z
    return newcirc
Esempio n. 24
0
def swap(s):
    if '*' not in s:
        if gmpy.is_prime(int(s)) > 0:
            solns.append(s)
        return
    for i in range(10):
        swap(s.replace('*', str(i)))
Esempio n. 25
0
def primegen():
    yield 2
    i = 3
    while True:
        if is_prime(i):
            yield i
        i += 2
Esempio n. 26
0
def sq(q):
    assert is_prime(q)
    p = 2
    while True:
	if p != q:
	    yield p*p*q*q*q
	p = int(next_prime(p))
Esempio n. 27
0
def get_primes():
    """Get primes up to 10000"""
    L = []
    for n in range(1, 10000, 2):
        if gmpy.is_prime(n) > 0:
            L.append(n)
    return L
Esempio n. 28
0
    def __init__(self,F,irpoly,g=None,rep=None):
        '''Define the base Field or extension Field and the irreducible polynomial
           F is the base field on top of which the extension
        field is built
           irpoly is the irreducible polynomial used to build
        the extension field as F/irpoly
           g is a non quadratic residue used to compute square
        roots, if it is set to None, computing a square root
        will initialize g
           rep is the representation of the root of irpoly
        (note that letter 'A' is reserved for the Complex extension field)
        '''
        self.F = F
        self.irpoly = irpoly
        self.deg = len(irpoly.coef) # degree of the irreducible polynomial + 1
        assert self.deg > 0
        self.q = self.F.q**(self.deg-1) # order of the Field

        self.tabular = self.table()

        if rep == None :
            self.rep = rd.choice(['B','C','D','E','F','G','H','J','K','L'])
            #Choose a random representation letter
        else :
            self.rep = rep

        self.char = F.char

        self.primefield = gmpy.is_prime(self.char)

        self.g = g # g is needed to compute square roots, it is a non quadratic residue

        self.to_fingerprint = ["F","irpoly"]
        self.to_export = {"fingerprint": [],"value": ["F","irpoly"]}
Esempio n. 29
0
def _find_safe_prime(bits, randfunc=None):
    """ Finds a safe prime of `bits` bits """
    r = gmpy.mpz(number.getRandomNBitInteger(bits-1, randfunc))
    q = gmpy.next_prime(r)
    p = 2*q+1
    if gmpy.is_prime(p):
        return p
Esempio n. 30
0
def extractkey(host, chunk, modulus):
	
    #print "\nChecking for private key...\n"
    n = int (modulus, 16)
    keysize = n.bit_length() / 16

    for offset in xrange (0, len (chunk) - keysize):
        p = long (''.join (["%02x" % ord (chunk[x]) for x in xrange (offset + keysize - 1, offset - 1, -1)]).strip(), 16)
        if gmpy.is_prime (p) and p != n and n % p == 0:
            if opts.verbose:
                print '\n\nFound prime: ' + str(p)
            e = 65537
            q = n / p
            phi = (p - 1) * (q - 1)
            d = gmpy.invert (e, phi)
            dp = d % (p - 1)
            dq = d % (q - 1)
            qinv = gmpy.invert (q, p)
            seq = Sequence()
            for x in [0, n, e, d, p, q, dp, dq, qinv]:
                seq.setComponentByPosition (len (seq), Integer (x))
            print "\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n" % base64.encodestring(encoder.encode (seq))
            privkeydump = open("hb-certs/privkey_" + host + ".dmp", "a")
            privkeydump.write(chunk)
            return True
        else:
            return False
Esempio n. 31
0
def calcprimes(N):
    primes.append(gmpy.mpz(2))
    i=gmpy.mpz(3)
    while(i<=N):
        if gmpy.is_prime(i)!=0:
            primes.append(i)
        i+=2
Esempio n. 32
0
def testLinearSystem(nbClients,maxexp=16,printing=False):
    assert not gmpy.is_prime(nbClients) is True
    cList = []
    for i in range(0,nbClients):
        cl = LS.LinearSystemPPATSClient(ppatspk,str(i))
        cList.append(cl)
    LSworker = LS.LinearSystemPPATSWorker(ppatspk,ppatssk,clientsList=cList)
    LSworker.makeCircuit()
    LSworker.fillInputGates(maxexp)
    if printing : print 'inputs received by worker'
    L = LSworker.decryptAndCheckProofs(printing)
    if printing : print 'inputs decrypted and proofs checked by worker'
    LSworker.recomInputs()
    if printing : print 'inputs recommited by worker'
    assert L == []
    LSworker.solveSystem(B=None,printing=printing)
    if printing : print 'Linear system solved by worker and proofs prepared'
    ldict = {'inputs':('ciphertext','message','opening','openingclear','consist'),'outputs':('ciphertext','consist'),'rest':('ciphertext','consist','message','opening','openingclear')}
    newcirc = LSworker.circuit.copy()
    newcirc.removeLevels(ldict)
    LSworker.sendCircuit(newcirc)
    cl0 = LSworker.clientsList[0]
    L = cl0.checkLSCircuitProofs(printing)
    assert L == []
    if printing : print 'Solution of the linear System is:\n',LSworker.Z
    return newcirc
Esempio n. 33
0
def main():
    n = int(sys.argv[2], 16)
    keysize = n.bit_length() / 16
    with open(sys.argv[1], "rb") as f:
        chunk = f.read(16384)
        while chunk:
            for offset in xrange(0, len(chunk) - keysize):
                p = long(
                    ''.join([
                        "%02x" % ord(chunk[x])
                        for x in xrange(offset + keysize - 1, offset - 1, -1)
                    ]).strip(), 16)
                if gmpy.is_prime(p) and p != n and n % p == 0:
                    e = 65537
                    q = n / p
                    phi = (p - 1) * (q - 1)
                    d = gmpy.invert(e, phi)
                    dp = d % (p - 1)
                    dq = d % (q - 1)
                    qinv = gmpy.invert(q, p)
                    seq = Sequence()
                    for x in [0, n, e, d, p, q, dp, dq, qinv]:
                        seq.setComponentByPosition(len(seq), Integer(x))
                        print "\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n" % base64.encodestring(
                            encoder.encode(seq))
                        sys.exit(0)
            chunk = f.read(16384)
        print "private key not found :("

        if __name__ == '__main__':
            main()
Esempio n. 34
0
def is_prime(n,
             rnd=default_pseudo_random,
             k=DEFAULT_ITERATION,
             algorithm=None):
    '''Test if n is a prime number

       m - the integer to test
       rnd - the random number generator to use for the probalistic primality
       algorithms,
       k - the number of iterations to use for the probabilistic primality
       algorithms,
       algorithm - the primality algorithm to use, default is Miller-Rabin. The
       gmpy implementation is used if gmpy is installed.

       Return value: True is n seems prime, False otherwise.
    '''

    if algorithm is None:
        algorithm = PRIME_ALGO
    if algorithm == 'gmpy-miller-rabin':
        if not gmpy:
            raise NotImplementedError
        return gmpy.is_prime(n, k)
    elif algorithm == 'miller-rabin':
        # miller rabin probability of primality is 1/4**k
        return miller_rabin(n, k, rnd=rnd)
    elif algorithm == 'solovay-strassen':
        # for jacobi it's 1/2**k
        return randomized_primality_testing(n, rnd=rnd, k=k * 2)
    else:
        raise NotImplementedError
Esempio n. 35
0
    def __init__(self, F, irpoly, g=None, rep=None):
        '''Define the base Field or extension Field and the irreducible polynomial
           F is the base field on top of which the extension
        field is built
           irpoly is the irreducible polynomial used to build
        the extension field as F/irpoly
           g is a non quadratic residue used to compute square
        roots, if it is set to None, computing a square root
        will initialize g
           rep is the representation of the root of irpoly
        (note that letter 'A' is reserved for the Complex extension field)
        '''
        self.F = F
        self.irpoly = irpoly
        self.deg = len(irpoly.coef)  # degree of the irreducible polynomial + 1
        assert self.deg > 0
        self.q = self.F.q**(self.deg - 1)  # order of the Field

        self.tabular = self.table()

        if rep == None:
            self.rep = rd.choice(
                ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L'])
            #Choose a random representation letter
        else:
            self.rep = rep

        self.char = F.char

        self.primefield = gmpy.is_prime(self.char)

        self.g = g  # g is needed to compute square roots, it is a non quadratic residue

        self.to_fingerprint = ["F", "irpoly"]
        self.to_export = {"fingerprint": [], "value": ["F", "irpoly"]}
Esempio n. 36
0
def is_prime(n, rnd=default_pseudo_random, k=DEFAULT_ITERATION, algorithm=None):
    '''Test if n is a prime number

       m - the integer to test
       rnd - the random number generator to use for the probalistic primality
       algorithms,
       k - the number of iterations to use for the probabilistic primality
       algorithms,
       algorithm - the primality algorithm to use, default is Miller-Rabin. The
       gmpy implementation is used if gmpy is installed.

       Return value: True is n seems prime, False otherwise.
    '''

    if algorithm is None:
        algorithm = PRIME_ALGO
    if algorithm == 'gmpy-miller-rabin':
        if not gmpy:
            raise NotImplementedError
        return gmpy.is_prime(n, k)
    elif algorithm == 'miller-rabin':
        # miller rabin probability of primality is 1/4**k
        return miller_rabin(n, k, rnd=rnd)
    elif algorithm == 'solovay-strassen':
        # for jacobi it's 1/2**k
        return randomized_primality_testing(n, rnd=rnd, k=k*2)
    else:
        raise NotImplementedError
Esempio n. 37
0
def is_prime(num):
    if gmpy.is_prime(num) > 0:
        return (True, num)
    for i in range(2,num):
        if (num % i) == 0:
            return (False, i)
        if i > 1000000:
            return (True, num)
Esempio n. 38
0
def is_primeproof(x):
    st = str(x)
    for i in range(len(st)):
        for d in range(10):
            stn = st[:i] + str(d) + st[i + 1:]
            if is_prime(int(stn)) and not stn.startswith('0'):
                return False
    return True
Esempio n. 39
0
def is_primeproof(x):
    st = str(x)
    for i in range(len(st)):
        for d in range(10):
            stn = st[:i] + str(d) + st[i+1:]
	    if is_prime(int(stn)) and not stn.startswith('0'):
		return False
    return True
Esempio n. 40
0
def is_prime(x):
    """
  Is prime x?
  Args:
    x : An integer
  Return: Is prime x?
  """
    return gmpy.is_prime(x) > 0
Esempio n. 41
0
def nextPrime(a):
	a|=1
	i=2
	while True:
		a+=2
		if gmpy.is_prime(a):	#0=composite, 1=maybe prime 2=surely prime
			return a
		
		i+=1
Esempio n. 42
0
def main(args):
    primes = 0
    for count, number in enumerate(gen()):
        if gmpy.is_prime(number):
            primes += 1
        if primes:
            if float(primes) / count <= args.ratio:
                print number, primes, count, int(ceil(count / 4.0) * 2 + 1)
                break
Esempio n. 43
0
 def prime_gen(k):
     """
     Prime number p in [2^(k/2-1), 2^(k/2).
     """
     assert k >= 1, "Sorry, need a bigger input"
     p = 0
     while not gmpy.is_prime(p):
         p = random.randrange(pow(2, k//2-1) + 1, pow(2, k//2), 2)
     return p
Esempio n. 44
0
def get_primes():
    """Get a list of all 4 digit prime numbers"""
    L = []
    for n in range(1000, 10000):
        if gmpy.is_prime(n) > 0:
            L.append(n)
        else:
            continue
    return L
Esempio n. 45
0
def phi(x):
    print(x)
    global phi_results

    if gmpy.is_prime(x):
        return x-1

    fac = prime_factors(x)
    result = int( x * reduce(mul, [(1-1.0/p) for p in fac]) )
    return result
Esempio n. 46
0
def find3(N, A = None):
    if A == None:
        A = gmpy.mpz(gmpy.sqrt(24*N)+1)
    k = A*A - 24*N
    assert gmpy.is_power(k)
    x = gmpy.sqrt(k)
    print x
    q1 =  (A - x)/4
    p1 = (A + x)/6

    q2 = (A + x)/4
    p2 = (A - x)/6
    
    if gmpy.is_prime(p1) and gmpy.is_prime(q1) and p1*q1==N:
        return p1, q1
    elif gmpy.is_prime(p2) and gmpy.is_prime(q2) and p2*q2==N:
        return p2, q2
    else:
        assert False
Esempio n. 47
0
def find3(N, A=None):
    if A == None:
        A = gmpy.mpz(gmpy.sqrt(24 * N) + 1)
    k = A * A - 24 * N
    assert gmpy.is_power(k)
    x = gmpy.sqrt(k)
    print x
    q1 = (A - x) / 4
    p1 = (A + x) / 6

    q2 = (A + x) / 4
    p2 = (A - x) / 6

    if gmpy.is_prime(p1) and gmpy.is_prime(q1) and p1 * q1 == N:
        return p1, q1
    elif gmpy.is_prime(p2) and gmpy.is_prime(q2) and p2 * q2 == N:
        return p2, q2
    else:
        assert False
Esempio n. 48
0
def pol_prime_length(a, b):
    '''
    Returns the maximum value of the argument of the polynom, at which polynom's value is a prime number
    '''
    n = 0
    while is_prime(n**2 + a * n + b):
        n += 1
    # XXX: Always returning product is inefficient.
    # XXX: Should compute it only for max() pair
    return n, a*b
Esempio n. 49
0
def calculate_division(test, n):
    # print n
    # print 'number of digits in test is {} in base 2'.format(_g.numdigits(test,2))
    # print 'number of digits in n is {} in base 2'.format(_g.numdigits(n,2))
    prime = _g.next_prime(test)
    # print prime
    if _g.is_prime(prime):
        # print 'I got a prime {}'.format(prime)
        if n % prime == 0:
            print n
            print 'success'
Esempio n. 50
0
def calculate_division(test, n):
    # print n
    # print 'number of digits in test is {} in base 2'.format(_g.numdigits(test,2))
    # print 'number of digits in n is {} in base 2'.format(_g.numdigits(n,2))
    prime = _g.next_prime(test)
    # print prime
    if _g.is_prime(prime):
        # print 'I got a prime {}'.format(prime)
        if n % prime == 0:
            print n
            print 'success'
Esempio n. 51
0
    def __init__(self, p=None, q=None, n=None, d=None, e=DEFAULT_EXP):
        """
        Initialize RSA instance using primes (p, q)
        or modulus and private exponent (n, d)
        """

        self.e = e

        if p and q:
            assert gmpy.is_prime(p), 'p is not prime'
            assert gmpy.is_prime(q), 'q is not prime'

            self.p = p
            self.q = q
        elif n and d:   
            self.p, self.q = factor_modulus(n, d, e)
        else:
            raise ArgumentError('Either (p, q) or (n, d) must be provided')

        self._calc_values()
Esempio n. 52
0
def count_safe_primes(bits):
    randfunc = Crypto.Random.new().read
    started = time.time()
    ret = []
    while True:
        r = gmpy.mpz(number.getRandomNBitInteger(bits-1, randfunc))
        q = gmpy.next_prime(r)
        p = 2*q + 1
        germain = gmpy.is_prime(p)
        ret.append((germain, int(q - r)))
        if time.time() - started > 60:
            break
    return ret
def makePrimeHarshads(max_digits, digits, aTotal):
    if digits == 0:
        for n in range(1, 10):
            yield (str(n))
    else:
        for harshad in makePrimeHarshads(max_digits, digits - 1, aTotal):
            for n in range(10):
                new_harshad = int(harshad + str(n))
                if isHarshad(new_harshad):
                    yield (str(new_harshad))
                elif is_prime(new_harshad):
                    if isStrongHarshad(int(harshad)):
                        #print(new_harshad)
                        aTotal[0] += new_harshad
Esempio n. 54
0
def El_Gamal_ParamGen():
    p = 4
    while not gmpy.is_prime(p):
        r = randint(0, 2**64)
        q = gmpy.next_prime(2**64 + r)
        p = 2 * q + 1
    g_prime = randint(1, int(p - 1))
    g = pow(g_prime, 2, p)  # generator of the group
    assert pow(g, q, p) == 1
    G = g, p, q
    x = randint(1, int(q - 1))  # secret key
    y = pow(g, x, p)  # public key
    pk = El_Gamal_PublicKey(G, y)
    sk = El_Gamal_SecretKey(G, x)
    return pk, sk
Esempio n. 55
0
def vuln_to_dlp(nbit):
    p = getPrime(nbit)
    q = 2
    while True:
        q *= getPrime(random.randint(5, 16))
        if q > 2**(nbit - 1):
            if gmpy.is_prime(q + 1) > 0:
                phi = (p - 1) * q
                n = p * (q + 1)
                while True:
                    e = random.randint(1, q)
                    d = gmpy.invert(e, phi)
                    if e * d % phi == 1:
                        return p, q + 1, n, e, phi, d
            else:
                q = 2
Esempio n. 56
0
def is_prime(x, k):
    y=0
    if k!=2:
        b=gmpy.mpz(1)
        while x>0:
            if x%2==1:
                y+=b
            x/=2
            b*=k
        x=y
    if(gmpy.is_prime(x)!=0):
        return 0
    for i in primes:
        if x%i==0:
            return i
        if i*i>x:
            break
    return 0
Esempio n. 57
0
    def __init__(self, p):
        '''Defines the modulus p which must be a prime
        '''
        self.F = self
        self.p = gmpy.mpz(p)  # prime modulus
        self.char = self.p  # characteristic
        self.q = self.p + 1  # order+1 #TODO : correct?
        assert gmpy.is_prime(p)
        self.rep = None
        self.g = None
        '''
        g is a random quadratic residue used to compute square roots and it is
        initialized the first time a square root is computed
        '''

        self.to_fingerprint = ["p"]
        self.to_export = {"fingerprint": [], "value": ["p"]}
        super(Field, self).__init__()