当前位置: 首页>>代码示例>>Python>>正文


Python number.getPrime方法代码示例

本文整理汇总了Python中Crypto.Util.number.getPrime方法的典型用法代码示例。如果您正苦于以下问题:Python number.getPrime方法的具体用法?Python number.getPrime怎么用?Python number.getPrime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Crypto.Util.number的用法示例。


在下文中一共展示了number.getPrime方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getprimeover

# 需要导入模块: from Crypto.Util import number [as 别名]
# 或者: from Crypto.Util.number import getPrime [as 别名]
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 
开发者ID:data61,项目名称:python-paillier,代码行数:21,代码来源:util.py

示例2: generatePrime

# 需要导入模块: from Crypto.Util import number [as 别名]
# 或者: from Crypto.Util.number import getPrime [as 别名]
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. 
开发者ID:reschly,项目名称:cryptopals,代码行数:13,代码来源:prob39.py

示例3: __init__

# 需要导入模块: from Crypto.Util import number [as 别名]
# 或者: from Crypto.Util.number import getPrime [as 别名]
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) 
开发者ID:ricpacca,项目名称:cryptopals,代码行数:13,代码来源:S5C39.py

示例4: handle_client

# 需要导入模块: from Crypto.Util import number [as 别名]
# 或者: from Crypto.Util.number import getPrime [as 别名]
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) 
开发者ID:ecthros,项目名称:pina-colada,代码行数:52,代码来源:server.py

示例5: generate_smooth_prime

# 需要导入模块: from Crypto.Util import number [as 别名]
# 或者: from Crypto.Util.number import getPrime [as 别名]
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') 
开发者ID:fbsamples,项目名称:fbctf-2019-challenges,代码行数:58,代码来源:dsks.py

示例6: generate_smooth_prime

# 需要导入模块: from Crypto.Util import number [as 别名]
# 或者: from Crypto.Util.number import getPrime [as 别名]
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') 
开发者ID:GrosQuildu,项目名称:CryptoAttacks,代码行数:60,代码来源:Math.py


注:本文中的Crypto.Util.number.getPrime方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。