Generate a random private key using sensible parameters.

    :param str key_type: The type of key to generate. One of: ``rsa``.
161503
def generate_private_key(key_type):
    
    if key_type == u'rsa':
        return rsa.generate_private_key(
            public_exponent=65537, key_size=2048, backend=default_backend())
    raise ValueError(key_type)
1178013
public static PrivateKey stringToRSAPrivateKey (String str)
    {
        try {
            BigInteger mod = new BigInteger(str.substring(0, str.indexOf(SPLIT)), 16);
            BigInteger exp = new BigInteger(str.substring(str.indexOf(SPLIT) + 1), 16);
            RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(mod, exp);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(keySpec);
        } catch (NumberFormatException nfe) {
            log.warning("Failed to read key from string.", "str", str, nfe);
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to read key from string.", "str", str, gse);
        }
        return null;
    }
105246
def CreateKey(self, private_key=None):
        
        if private_key is None:
            private_key = bytes(Random.get_random_bytes(32))

        key = KeyPair(priv_key=private_key)
        self._keys[key.PublicKeyHash.ToBytes()] = key
        return key
643674
def generate_public_key(self):
        
        self.public_key = pow(self.generator,
                              self.__private_key,
                              self.prime)
337218
def private_key_to_address(self, pk):
        
        pub = privtopub(pk)
        pub_byte, priv_byte = get_magic_bytes(self.crypto)

        if priv_byte >= 128:
            priv_byte -= 128 #pybitcointools bug

        return pubtoaddr(pub, pub_byte)
1248826
public static Optional<Key> buildRSAPublicKey(final String keyType, final BigInteger modulus,
            final BigInteger exponent) {
        try {
            return of(KeyFactory.getInstance(keyType).generatePublic(new RSAPublicKeySpec(modulus, exponent)));
        } catch (final NoSuchAlgorithmException | InvalidKeySpecException ex) {
            LOGGER.error("Error generating RSA Key from JWKS entry", ex);
        }
        return empty();
    }
1320385
def generate_rsa_key_pair():
    """"""

    key = rsa.generate_private_key(
        backend=default_backend(), public_exponent=65537, key_size=2048)

    public_key = key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH).decode("utf-8")

    pem = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()).decode("utf-8")

    return public_key, pem
1195835
def DecryptPrivateKey(self, encrypted_private_key):
        
        aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
        return aes.decrypt(encrypted_private_key)
557411
def GenerateKeys(config, overwrite_keys=False):
  """"""
  if not hasattr(key_utils, "MakeCACert"):
    raise OpenSourceKeyUtilsRequiredError(
        "Generate keys can only run with open source key_utils.")
  if (config.Get("PrivateKeys.server_key", default=None) and
      not overwrite_keys):
    print(config.Get("PrivateKeys.server_key"))
    raise KeysAlreadyExistError(
        "Config %s already has keys, use --overwrite_keys to "
        "override." % config.parser)

  length = grr_config.CONFIG["Server.rsa_key_length"]
  print("All keys will have a bit length of %d." % length)
  print("Generating executable signing key")
  executable_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  config.Set("PrivateKeys.executable_signing_private_key",
             executable_key.AsPEM())
  config.Set("Client.executable_signing_public_key",
             executable_key.GetPublicKey().AsPEM())

  print("Generating CA keys")
  ca_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  ca_cert = key_utils.MakeCACert(ca_key)
  config.Set("CA.certificate", ca_cert.AsPEM())
  config.Set("PrivateKeys.ca_key", ca_key.AsPEM())

  print("Generating Server keys")
  server_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  server_cert = key_utils.MakeCASignedCert(u"grr", server_key, ca_cert, ca_key)
  config.Set("Frontend.certificate", server_cert.AsPEM())
  config.Set("PrivateKeys.server_key", server_key.AsPEM())

  print("Generating secret key for csrf protection.")
  _GenerateCSRFKey(config)
1084671
def from_private_key(path: str) -> SigningKeyType:
        
        key = load_key(path)
        key.pubkey = Base58Encoder.encode(key.vk)
        return key
601801
def derive_key_block(self, master_secret, server_random,
                         client_random, req_len):
        
        seed = server_random + client_random
        if self.tls_version <= 0x0300:
            return self.prf(master_secret, seed, req_len)
        else:
            return self.prf(master_secret, b"key expansion", seed, req_len)
176070
def generate_keypair(crypto, seed, password=None):
    
    if crypto in ['eth', 'etc']:
        raise CurrencyNotSupported("Ethereums not yet supported")

    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        # pycrypto etc. must be installed or this will raise ImportError, hence inline import.
        from .bip38 import Bip38EncryptedPrivateKey
        priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)

    return ret
1243587
def _random_key(self):
        
        hashstr = '%s%s' % (random.random(), self.time_module.time())
        return hashlib.md5(hashstr).hexdigest()
1074176
def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
                                        digest=DEFAULT_DIGEST):
    '''
        
    '''
    private_key = OpenSSL.crypto.PKey()
    private_key.generate_key(TYPE_RSA, size)

    request = OpenSSL.crypto.X509Req()
    subject = request.get_subject()
    setattr(subject, 'CN', common_name)
    request.set_pubkey(private_key)
    request.sign(private_key, digest)

    certificate = OpenSSL.crypto.X509()
    certificate.set_serial_number(0)
    certificate.gmtime_adj_notBefore(0)
    certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 5)
    certificate.set_issuer(request.get_subject())
    certificate.set_subject(request.get_subject())
    certificate.set_pubkey(request.get_pubkey())
    certificate.sign(private_key, digest)

    private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(private_key_path):
        print 'Write {}'.format(private_key_path)
        with open(private_key_path, 'w+') as private_key_file:
            private_key_file.write(
                OpenSSL.crypto.dump_privatekey(FILETYPE_PEM,
                                               private_key).decode('utf-8')
            )
        helpers.file_rights(private_key_path, mode=0400, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(private_key_path)

    certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(certificate_path):
        print 'Write {}'.format(certificate_path)
        with open(certificate_path, 'w+') as certificate_file:
            certificate_file.write(
                OpenSSL.crypto.dump_certificate(FILETYPE_PEM,
                                                certificate).decode('utf-8')
            )
        helpers.file_rights(certificate_path, mode=0444, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(certificate_path)

    clean_links()
    make_links(common_name)
25832
def generate(cls):
        
        return cls(libnacl.randombytes(PrivateKey.SIZE), encoder=encoding.RawEncoder)
360193
def gen_private_key(filepath, silent=False):
    
    cmd = 'openssl genrsa -out {} 2048'.format(filepath)
    message = 'generate private key {}'.format(filepath)
    call_openssl(cmd, message, silent)
1210097
def key_type(key, host=None, port=None, db=None, password=None):
    '''
    
    '''
    server = _connect(host, port, db, password)
    return server.type(key)