Python Crypto.Util.number 模块,getPrime() 实例源码

我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用Crypto.Util.number.getPrime()

项目:ctf-library    作者:Hcamael    | 项目源码 | 文件源码
def gen_key():
    while True:
        p = getPrime(k/2)
        if gcd(e, p-1) == 1:
            break
    q_t = getPrime(k/2)
    n_t = p * q_t
    t = get_bit(n_t, k/16, 1)
    y = get_bit(n_t, 5*k/8, 0)
    p4 = get_bit(p, 5*k/16, 1)
    u = pi_b(p4, 1)
    n = bytes_to_long(long_to_bytes(t) + long_to_bytes(u) + long_to_bytes(y))
    q = n / p
    if q % 2 == 0:
        q += 1
    while True:
        if isPrime(q) and gcd(e, q-1) == 1:
            break
        m = getPrime(k/16) + 1
        q ^= m
    return (p, q, e)
项目:ctf-library    作者:Hcamael    | 项目源码 | 文件源码
def get_pkey():
    print "DH key exchange system:"
    P = getPrime(m)
    print "P: ", hex(P)
    G = getRandomNBitInteger(m)
    a = getRandomNBitInteger(m/4)
    Ya = pow(G, a, P)
    print "Please enter you secret key: "
    try:
        b = raw_input()
        b = int(b)
        assert size(b) == m/4
    except:
        m_exit(-1)
    Yb = pow(G, b, P)
    K = pow(Yb, a, P)
    return (Ya, K)
项目:about-cryptography    作者:L1nwatch    | 项目源码 | 文件源码
def __init__(self, p=None, q=None, bit_length=512, e=None):
        """
        ?? p ? q, ??????? bit_length ??????????
        :param p: ?? p
        :param q: ?? q
        :param bit_length: ??????
        """
        if p and q and gmpy2.is_prime(p) and gmpy2.is_prime(q):
            self.p = p
            self.q = q
        else:
            print("[*] ?????? p ? q, ???????")
            self.p = getPrime(bit_length)
            self.q = getPrime(bit_length)

        self.__create_rsa(e)
项目:about-cryptography    作者:L1nwatch    | 项目源码 | 文件源码
def generate_public_key(bits_length=512, e=3):
    """
    ???? RSA ?????, p, q, e
    :param bits_length: ??? p ? q ??????
    :param e: 3
    :return: n, e
    """
    # ??????????, ?? phi(N) ? e ??
    while True:
        p = getPrime(bits_length)
        q = getPrime(bits_length)
        n = gmpy2.mpz(p) * gmpy2.mpz(q)
        phi_n = gmpy2.mpz(p - 1) * gmpy2.mpz(q - 1)

        if gmpy2.gcd(phi_n, e) == 1:
            return n, e
项目:cryptopal    作者:lanjelot    | 项目源码 | 文件源码
def gen_prime_given_e(bitlen, e):
  while True:
    p = get_prime(bitlen)
    if p % e != 1:
      return p
项目:ctf-library    作者:Hcamael    | 项目源码 | 文件源码
def get_ed(p, q):
    k = cal_bit(q*p)
    phi_n = (p-1)*(q-1)
    r = random.randint(10, 99)
    while True:
        u = getPrime(k/4 - r)
        if gcd(u, phi_n) != 1:
            continue
        t = invmod(u, phi_n)
        e = pi_b(t)
        if gcd(e, phi_n) == 1:
            break
    d = invmod(e, phi_n)
    return (e, d)
项目:ctf-library    作者:Hcamael    | 项目源码 | 文件源码
def getBlumPrime(nbits):
    p = getPrime(nbits)
    while p % 4 != 3:
        p = getPrime(nbits)
    return p
项目:about-cryptography    作者:L1nwatch    | 项目源码 | 文件源码
def create_rsa_keys(bits_length=1024, e=65537):
    """
    ???? RSA ?????, ?? p, q, n ,phi_n, d, e
    ???? pycrypto ?? RSA ????, ????????? 1024bits, ???????
    :param bits_length: p ? q ??????
    :param e: ??? e
    :return: dict(), RSA ???????????
    """
    rsa = dict()
    while True:
        p = gmpy2.mpz(getPrime(bits_length))
        q = gmpy2.mpz(getPrime(bits_length))
        n = p * q
        phi_n = (p - 1) * (q - 1)

        if gmpy2.gcd(e, phi_n) == 1:
            break

    rsa["p"] = p
    rsa["q"] = q
    rsa["n"] = n
    rsa["phi"] = phi_n
    rsa["d"] = gmpy2.invert(e, rsa["phi"])
    rsa["e"] = e

    return rsa
项目:about-cryptography    作者:L1nwatch    | 项目源码 | 文件源码
def create_rsa_keys(bits_length=512, e=65537):
    """
    ???? RSA ?????, ?? p, q, n ,phi_n, d, e
    ???? pycrypto ?? RSA ????, ????????? 1024bits, ???????
    :param bits_length: p ? q ??????
    :param e: ??? e
    :return: dict(), RSA ???????????
    """
    rsa = dict()
    while True:
        p = gmpy2.mpz(getPrime(bits_length))
        q = gmpy2.mpz(getPrime(bits_length))
        n = p * q
        phi_n = (p - 1) * (q - 1)

        if gmpy2.gcd(e, phi_n) == 1:
            break

    rsa["p"] = p
    rsa["q"] = q
    rsa["n"] = n
    rsa["phi"] = phi_n
    rsa["d"] = gmpy2.invert(e, rsa["phi"])
    rsa["e"] = e

    return rsa


# ????????chall41?code
项目:pina-colada    作者:ecthros    | 项目源码 | 文件源码
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)
项目:ctf-library    作者:Hcamael    | 项目源码 | 文件源码
def main():
    verify()
    usage = """
 **       **          **                                **********         
/**      /**         /**                               /////**///          
/**   *  /**  *****  /**  *****   ******  **********       /**      ****** 
/**  *** /** **///** /** **///** **////**//**//**//**      /**     **////**
/** **/**/**/******* /**/**  // /**   /** /** /** /**      /**    /**   /**
/**** //****/**////  /**/**   **/**   /** /** /** /**      /**    /**   /**
/**/   ///**//****** ***//***** //******  *** /** /**      /**    //****** 
//       //  ////// ///  /////   //////  ///  //  //       //      //////  

 **      **   ******  ********** ********   *******    ********     **    
/**     /**  **////**/////**/// /**/////   /**////**  **//////     ****   
/**     /** **    //     /**    /**        /**   /** /**          **//**  
/**********/**           /**    /*******   /*******  /*********  **  //** 
/**//////**/**           /**    /**////    /**///**  ////////** **********
/**     /**//**    **    /**    /**        /**  //**        /**/**//////**
/**     /** //******     /**    /**        /**   //** ******** /**     /**
//      //   //////      //     //         //     // ////////  //      // 

   ********                               
  **//////**                              
 **      //   ******   **********   ***** 
/**          //////** //**//**//** **///**
/**    *****  *******  /** /** /**/*******
//**  ////** **////**  /** /** /**/**//// 
 //******** //******** *** /** /**//******
  ////////   //////// ///  //  //  ////// 
    """
    print usage
    print "This is a RSA Decryption System"
    print "Please enter Your team token: "
    token = raw_input()
    try:
        flag = get_flag(token)
        assert len(flag) == 38
    except:
        print "Token error!"
        m_exit(-1)

    p=getPrime(2048)
    q=getPrime(2048)
    n = p * q
    e, d = get_ed(p, q)
    print "n: ", hex(n)
    print "e: ", hex(e)

    flag = bytes_to_long(flag)
    enc_flag = pow(flag, e, n)
    print "Your flag is: ", hex(enc_flag)
项目:helios-server-mixnet    作者:RunasSudo    | 项目源码 | 文件源码
def _generate_safe_prime(nbits, probability=params.FALSE_PRIME_PROBABILITY, 
                         task_monitor=None):
        """
        Generate a safe prime of size nbits.

        A safe prime is one of the form p = 2q + 1, where q is also a prime. 
        The prime p used for ElGamal must be a safe prime, otherwise some 
        attacks that rely on factoring the order p - 1 of the cyclic group 
        Z_{p}^{*} may become feasible if p - 1 does not have a large prime 
        factor. (p = 2q + 1, means p - 1 = 2q, which has a large prime factor,
        namely q)

        Arguments:
            nbits::int    -- Bit size of the safe prime p to generate. 
                           This private method assumes that the
                           nbits parameter has already been checked to satisfy 
                           all necessary security conditions.
            probability::int    -- The desired maximum probability that p 
                                   or q may be composite numbers and still be 
                                   declared prime by our (probabilistic) 
                                   primality test. (Actual probability is 
                                   lower, this is just a maximum provable bound)
            task_monitor::TaskMonitor    -- A task monitor for the process.

        Returns:
            p::long        -- A safe prime.
        """
        found = False

        # We generate (probable) primes q of size (nbits - 1) 
        # until p = 2*q + 1 is also a prime
        while(not found):
            if(task_monitor != None): task_monitor.tick()

            q = number.getPrime(nbits - 1)
            p = 2*q + 1

            if(not number.isPrime(p, probability)):
                continue

            # Are we sure about q, though? (pycrypto may allow a higher 
            # probability of q being composite than what we might like)
            if(not number.isPrime(q, probability)):
                continue    # pragma: no cover (Too rare to test for)

            found = True

        # DEBUG CHECK: The prime p must be of size n=nbits, that is, in 
        # [2**(n-1),2**n] (and q must be of size nbits - 1)
        if(params.DEBUG):
            assert 2**(nbits - 1) < p < 2**(nbits), \
                    "p is not an nbits prime."
            assert 2**(nbits - 2) < q < 2**(nbits - 1), \
                    "q is not an (nbits - 1) prime"

        return p
项目:helios-server-mixnet    作者:RunasSudo    | 项目源码 | 文件源码
def _generate_safe_prime(nbits, probability=params.FALSE_PRIME_PROBABILITY, 
                         task_monitor=None):
        """
        Generate a safe prime of size nbits.

        A safe prime is one of the form p = 2q + 1, where q is also a prime. 
        The prime p used for ElGamal must be a safe prime, otherwise some 
        attacks that rely on factoring the order p - 1 of the cyclic group 
        Z_{p}^{*} may become feasible if p - 1 does not have a large prime 
        factor. (p = 2q + 1, means p - 1 = 2q, which has a large prime factor,
        namely q)

        Arguments:
            nbits::int    -- Bit size of the safe prime p to generate. 
                           This private method assumes that the
                           nbits parameter has already been checked to satisfy 
                           all necessary security conditions.
            probability::int    -- The desired maximum probability that p 
                                   or q may be composite numbers and still be 
                                   declared prime by our (probabilistic) 
                                   primality test. (Actual probability is 
                                   lower, this is just a maximum provable bound)
            task_monitor::TaskMonitor    -- A task monitor for the process.

        Returns:
            p::long        -- A safe prime.
        """
        found = False

        # We generate (probable) primes q of size (nbits - 1) 
        # until p = 2*q + 1 is also a prime
        while(not found):
            if(task_monitor != None): task_monitor.tick()

            q = number.getPrime(nbits - 1)
            p = 2*q + 1

            if(not number.isPrime(p, probability)):
                continue

            # Are we sure about q, though? (pycrypto may allow a higher 
            # probability of q being composite than what we might like)
            if(not number.isPrime(q, probability)):
                continue    # pragma: no cover (Too rare to test for)

            found = True

        # DEBUG CHECK: The prime p must be of size n=nbits, that is, in 
        # [2**(n-1),2**n] (and q must be of size nbits - 1)
        if(params.DEBUG):
            assert 2**(nbits - 1) < p < 2**(nbits), \
                    "p is not an nbits prime."
            assert 2**(nbits - 2) < q < 2**(nbits - 1), \
                    "q is not an (nbits - 1) prime"

        return p