Python Crypto.Util.number.getPrime() Examples

The following are 6 code examples of Crypto.Util.number.getPrime(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Crypto.Util.number , or try the search function .
Example #1
Source File: util.py    From python-paillier with GNU General Public License v3.0 6 votes vote down vote up
def getprimeover(N):
    """Return a random N-bit prime number using the System's best
    Cryptographic random source.

    Use GMP if available, otherwise fallback to PyCrypto
    """
    if HAVE_GMP:
        randfunc = random.SystemRandom()
        r = gmpy2.mpz(randfunc.getrandbits(N))
        r = gmpy2.bit_set(r, N - 1)
        return int(gmpy2.next_prime(r))
    elif HAVE_CRYPTO:
        return number.getPrime(N, os.urandom)
    else:
        randfunc = random.SystemRandom()
        n = randfunc.randrange(2**(N-1), 2**N) | 1
        while not is_prime(n):
            n += 2
        return n 
Example #2
Source File: prob39.py    From cryptopals with Apache License 2.0 5 votes vote down vote up
def generatePrime(bits):
    return getPrime(bits);
    
    
# The second is that you need an "invmod" operation (the multiplicative
# inverse), which is not an operation that is wired into your
# language. The algorithm is just a couple lines, but I always lose an
# hour getting it to work.

# I recommend you not bother with primegen, but do take the time to get
# your own EGCD and invmod algorithm working. 
Example #3
Source File: S5C39.py    From cryptopals with MIT License 5 votes vote down vote up
def __init__(self, key_length):
        """In this exercise, e is fixed to 3 so we will have to find p and q that fit the requirements."""
        self.e = 3
        phi = 0

        while gcd(self.e, phi) != 1:
            p, q = getPrime(key_length // 2), getPrime(key_length // 2)
            phi = lcm(p - 1, q - 1)
            self.n = p * q

        self._d = mod_inv(self.e, phi) 
Example #4
Source File: server.py    From pina-colada with MIT License 4 votes vote down vote up
def handle_client(self, c, cid):
        try:
            #Diffie-Helmen Exchange
            shared_prime = number.getPrime(10)
            shared_base = number.getPrime(10)
            server_secret = random.randint(0, 99)
            c.send(str(shared_prime) + "|" + str(shared_base) + "~")
            a = ((shared_base**server_secret) % shared_prime)
            print "sending %s to client" %( str(shared_prime) + "|" + str(shared_base))
            c.send("%ld~" % a)  # send A
            b = long(c.recv(1024))  # receive B
            print "got %ld from client" % b
            self.keys[c] = pad("%ld" % ((b ** server_secret) % shared_prime))
            print self.keys[c]
            n = c.recv(1024)
            print n
            print self.decrypt(n, c)
            _, name, name = self.unpack_data(self.decrypt(n, c))
            name = name.replace(END_SEP, "").replace(SEP, "")
            print("(%s)" % name)
            self.ids[cid] = name
            self.clients[cid] = c
            if name == "PinaColada":
                self.pi = c
                app.config["server"] = self
                print "[*] Pina Colada has connected."
            else:
                print '[*] Tunnel initialized for user %s' % name
                self.tunnels[cid] = c

        except Exception as e:
            self.print_exc(e, "\n[!] Failed to initialize client connection for %d." % id, always=True)
            self.close(cid)
            traceback.print_exc()
            return False
        try:
            while True:
                d = c.recv(1024)
                print d
                print self.decrypt(d, c)
                msgs = filter(None, self.decrypt(d, c).split(END_SEP))
                print msgs
                for m in msgs:
                    self.inbound(m, c)
                #print d

        except Exception as e:
            self.print_exc(e, "")
            print("[!] Connection closed from client %d (%s) - %s" % (cid, self.ids[cid], self.ips[cid]))
            self.close(cid) 
Example #5
Source File: dsks.py    From fbctf-2019-challenges with MIT License 4 votes vote down vote up
def generate_smooth_prime(bit_size, primitive_roots=[], smooth_bit_size=50, exclude=[]):
    """Generate smooth prime n
    Args:
        bit_size(int): size of generated prime in bits
        primitive_roots(list(int)): list of numbers that will be primitive roots modulo n
        smooth_bit_size(int): most factors of n-1 will be of this bit size   
        exclude(list(int)): n-1 won't have any factor from that list
    Returns:
        int: n
    """
    while True:
        n = 2
        factors = {2:1}

        # get random primes of correct size
        print('smooth prime - loop of size about {}'.format((bit_size - 2*smooth_bit_size)//smooth_bit_size))
        while n.bit_length() < bit_size - 2*smooth_bit_size:
            q = getPrime(smooth_bit_size)
            if q in exclude:
                continue
            n *= q
            if q in factors:
                factors[q] += 1
            else:
                factors[q] = 1

        # find last prime so that n+1 is prime and the size is correct
        smooth_bit_size_padded = bit_size - n.bit_length()
        print('smooth prime - smooth_bit_size_padded = {}'.format(smooth_bit_size_padded))
        while True:
            q = getPrime(smooth_bit_size_padded)
            if q in exclude:
                continue
            if isPrime((n*q)+1):
                n = (n*q)+1
                if q in factors:
                    factors[q] += 1
                else:
                    factors[q] = 1
                break
        
        # check if given numbers are primitive roots
        print('smooth prime - checking primitive roots')
        are_primitive_roots = True
        if len(primitive_roots) > 0: 
            for factor, factor_power in factors.items():
                for primitive_root in primitive_roots:
                    if pow(primitive_root, (n-1)//(factor**factor_power), n) == 1:
                        are_primitive_roots = False
                        break

        if are_primitive_roots:
            print('smooth prime - done')
            return n, factors
        else:
            print('primitive roots criterion not met') 
Example #6
Source File: Math.py    From CryptoAttacks with MIT License 4 votes vote down vote up
def generate_smooth_prime(bit_size, primitive_roots=[], smooth_bit_size=50, exclude=[]):
    """Generate smooth prime n

    Args:
        bit_size(int): size of generated prime in bits
        primitive_roots(list(int)): list of numbers that will be primitive roots modulo n
        smooth_bit_size(int): most factors of n-1 will be of this bit size   
        exclude(list(int)): n-1 won't have any factor from that list

    Returns:
        int: n
    """
    while True:
        n = 2
        factors = {2:1}

        # get random primes of correct size
        log.debug('smooth prime - loop of size about {}'.format((bit_size - 2*smooth_bit_size)//smooth_bit_size))
        while n.bit_length() < bit_size - 2*smooth_bit_size:
            q = getPrime(smooth_bit_size)
            if q in exclude:
                continue
            n *= q
            if q in factors:
                factors[q] += 1
            else:
                factors[q] = 1

        # find last prime so that n+1 is prime and the size is correct
        smooth_bit_size_padded = bit_size - n.bit_length()
        log.debug('smooth prime - smooth_bit_size_padded = {}'.format(smooth_bit_size_padded))
        while True:
            q = getPrime(smooth_bit_size_padded)
            if q in exclude:
                continue
            if isPrime((n*q)+1):
                n = (n*q)+1
                if q in factors:
                    factors[q] += 1
                else:
                    factors[q] = 1
                break
        
        # check if given numbers are primitive roots
        log.debug('smooth prime - checking primitive roots')
        are_primitive_roots = True
        if len(primitive_roots) > 0: 
            for factor, factor_power in factors.items():
                for primitive_root in primitive_roots:
                    if pow(primitive_root, (n-1)//(factor**factor_power), n) == 1:
                        are_primitive_roots = False
                        break

        if are_primitive_roots:
            log.debug('smooth prime - done')
            return n, factors
        else:
            log.debug('primitive roots criterion not met')