Use this API to create ssldsakey.
556257
public static base_response create(nitro_service client, ssldsakey resource) throws Exception {
		ssldsakey createresource = new ssldsakey();
		createresource.keyfile = resource.keyfile;
		createresource.bits = resource.bits;
		createresource.keyform = resource.keyform;
		createresource.des = resource.des;
		createresource.des3 = resource.des3;
		createresource.password = resource.password;
		return createresource.perform_operation(client,"create");
	}
658539
private static RestClient buildRestClient(List<InetSocketTransportAddress> hosts, int threadCount, boolean sslEnabled,
      String keyStoreType, String keyStoreFilePassword, String identityFilepath, String trustStoreType,
      String trustStoreFilePassword, String cacertsFilepath) throws Exception {


    HttpHost[] httpHosts = new HttpHost[hosts.size()];
    String scheme = sslEnabled?"https":"http";
    for (int h = 0; h < httpHosts.length; h++) {
      InetSocketTransportAddress host = hosts.get(h);
      httpHosts[h] = new HttpHost(host.getAddress(), host.getPort(), scheme);
    }

    RestClientBuilder builder = RestClient.builder(httpHosts);

    if (sslEnabled) {
      log.info("ssl configuration: trustStoreType = {}, cacertsFilePath = {}", trustStoreType, cacertsFilepath);
      KeyStore truststore = KeyStore.getInstance(trustStoreType);
      FileInputStream trustInputStream = new FileInputStream(cacertsFilepath);
      try {
        truststore.load(trustInputStream, trustStoreFilePassword.toCharArray());
      }
      finally {
        trustInputStream.close();
      }
      SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null);

      log.info("ssl key configuration: keyStoreType = {}, keyFilePath = {}", keyStoreType, identityFilepath);

      KeyStore keystore = KeyStore.getInstance(keyStoreType);
      FileInputStream keyInputStream = new FileInputStream(identityFilepath);
      try {
        keystore.load(keyInputStream, keyStoreFilePassword.toCharArray());
      }
      finally {
        keyInputStream.close();
      }
      sslBuilder.loadKeyMaterial(keystore, keyStoreFilePassword.toCharArray());

      final SSLContext sslContext = sslBuilder.build();
      builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
          // Set ssl context
          .setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier())
          // Configure number of threads for clients
          .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build()));
    } else {
      builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
          // Configure number of threads for clients
          .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build()));
    }

    // Configure timeouts
    builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
        .setConnectionRequestTimeout(0)); // Important, otherwise the client has spurious timeouts

    return builder.build();
  }
1098572
public SSLSocket buildSocket() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException, KeyManagementException
    {
        if (host == null) throw new IllegalStateException("Cannot create socket without host");

        // Get socket
        final SSLSocket s = (SSLSocket) build().getSocketFactory().createSocket(host, port);

        // Set protocols
        s.setEnabledProtocols(TLS.getUsable(TLS.TLS_PROTOCOLS, s.getSupportedProtocols()));
        s.setEnabledCipherSuites(TLS.getUsable(TLS.TLS_CIPHER_SUITES, s.getSupportedCipherSuites()));

        return s;
    }
283302
def create_key(file_):
    
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    file_.flush()
880289
def generate_keystore(key_alias, key_folder='./', root_cert='', truststore='', password='', organization='', organization_unit='', locality='', country='', key_size=2048, verbose=True, overwrite=False):

    '''  '''

    title = 'generate_keystore'
    
# import dependencies
    import os
    from subprocess import call, STDOUT, Popen, PIPE
    DEVNULL = open(os.devnull, 'w')

# define system call
    def _call(sys_command, ignore='', prompt_input='', title=''):
        if title and verbose:
            print('%s ... ' % title, end='', flush=True)
        p = Popen(sys_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
        if prompt_input:
            stdout, stderr = p.communicate(str('%s\n' % prompt_input).encode('utf-8'))
        if p.returncode != 0:
            cmd_err = p.stdout.read().decode()
            if not cmd_err:
                pass
            elif ignore:
                if not cmd_err.find(ignore) > -1:
                    raise Exception(cmd_err)
            else:
                if title and verbose:
                    print('ERROR.')
                raise Exception(cmd_err)
        if title and verbose:
            print('done.')

# verify libraries
    try:
        call('openssl version', shell=True, stdout=DEVNULL)
    except:
        raise Exception('%s requires openssl library. try: sudo apt-get install openssl' % title)
    try:
        _call('keytool -help', ignore='Key and Certificate Management Tool')
    except:
        raise Exception('%s requires keytool library. try: sudo apt-get install openjdk-8-jre' % title)

# validate input
    if not isinstance(key_alias, str):
        raise ValueError('%s(key_alias="...") must be a string datatype.' % title)
    if not key_size in (2048, 4096):
        raise ValueError('%s(key_size=%s must be either 2048 or 4096' % (title, key_size))
    import re
    input_fields = {
        'organization': organization,
        'organization_unit': organization_unit,
        'locality': locality,
        'country': country
    }
    for key, value in input_fields.items():
        if re.findall('[^\w_\-\s]', value):
            raise ValueError('%s(%s="%s") must contain only alphanumeric characters, _, - and spaces.' % (title, key, value))

# construct key folder
    from os import path, makedirs, remove
    if not path.exists(key_folder):
        makedirs(key_folder)
    elif not path.isdir(key_folder):
        raise ValueError('%s(key_folder="%s") must be a directory.' % (title, key_folder))

# validate cert path
    cert_path = path.join(key_folder, '%s.crt' % key_alias)
    if path.exists(cert_path) and not overwrite:
        raise ValueError('%s.crt already exists in %s. to overwrite, set overwrite=true' % (key_alias, key_folder))

# validate root path
    from copy import deepcopy
    root_cert_copy = deepcopy(root_cert)
    if root_cert_copy:
        if not path.exists(root_cert_copy):
            root_cert_copy = path.join(key_folder, root_cert_copy)
            if not path.exists(root_cert_copy):
                raise ValueError('%s(root_cert="%s") is not a valid path.' % (title, root_cert_copy))
        root_node, root_ext = path.splitext(root_cert_copy)
        root_key = root_node + '.key'
        if not root_ext in ('.crt', '.pem'):
            raise ValueError('%s(root_cert="%s") must be a .crt or .pem file type.' % (title, root_cert_copy))
        elif not path.exists(root_key):
            key_path, key_name = path.split(root_key)
            raise ValueError('%s(root_cert="%s") requires a matching private key %s' % (title, root_cert_copy, key_name))
        root_path = root_cert_copy
        key_path = root_path.replace('.crt', '.key')
    else:
        key_path = path.join(key_folder, 'root.key')
        root_path = path.join(key_folder, 'root.crt')
        if path.exists(root_path) and not overwrite:
            raise ValueError('root.crt already exists in %s. to overwrite, set overwrite=true' % key_folder)

# validate truststore path
    truststore_copy = deepcopy(truststore)
    if truststore_copy:
        if not path.exists(truststore_copy):
            truststore_copy = path.join(key_folder, truststore_copy)
            if not path.exists(truststore_copy):
                raise ValueError('%s(truststore="%s") is not a valid path.' % (title, truststore_copy))
        trust_node, trust_ext = path.splitext(truststore_copy)
        if not trust_ext in ('.jks'):
            raise ValueError('%s(truststore="%s") must be a .jks file type.' % (title, truststore_copy))
        truststore_path = truststore_copy
        trust_root, trust_node = path.split(truststore_path)
        trust_alias, trust_ext = path.splitext(trust_node)
    else:
        truststore_path = path.join(key_folder, 'truststore.jks')
        trust_alias = 'truststore'
        if path.exists(truststore_path) and not overwrite:
            raise ValueError('%s.jks already exists in %s. to overwrite, set overwrite=true' % (trust_alias, key_folder))

# format DNAME fields
    if not organization:
        organization = 'None'
    if not organization_unit:
        organization_unit = 'None'
    if not locality:
        locality = 'None'
    if not country:
        country = 'None'

# create root certificate
    if not root_cert_copy:
        subject_args = '/CN=root/OU=%s/O=%s/L=%s/C=%s' % (
            organization_unit,
            organization,
            locality,
            country
        )
        root_subject = '-subj %s' % subject_args.replace(' ', '\ ')
        password_text = '-passout pass:%s' % password
        sys_command = 'openssl req -newkey rsa:%s -x509 -nodes -keyout %s -out %s -days 36500 %s %s' % (key_size, key_path, root_path, root_subject, password_text)
        _call(sys_command, ignore='writing new private key', title='Generating root certificate')

# generate server cert
    server_dname = '-dname "CN=%s, OU=%s, O=%s, L=%s, C=%s"' % (
        key_alias, organization_unit, organization, locality, country
    )
    keystore_path = path.join(key_folder, '%s.jks' % key_alias)
    if path.exists(keystore_path) and not overwrite:
        raise ValueError('%s.jks already exists in %s. to overwrite, set overwrite=true' % (key_alias, key_folder))
    elif path.exists(keystore_path):
        remove(keystore_path)
    sys_command = 'keytool -genkey -keyalg RSA -alias %s -validity 36500 -keystore %s -storepass %s -keypass %s -keysize %s %s' % (key_alias, keystore_path, password, password, key_size, server_dname)
    _call(sys_command, ignore='JKS keystore uses a proprietary format', title='Generating keystore for %s' % key_alias)

# convert cert to pkcs12
    sys_command = 'keytool -importkeystore -srckeystore %s -destkeystore %s -deststoretype pkcs12 -storepass %s -keypass %s' % (keystore_path, keystore_path, password, password)
    _call(sys_command, prompt_input=password, title='Converting keystore to pkcs12 standard')
    remove('%s.old' % keystore_path)

# generate certificate request
    request_path = path.join(key_folder, '%s.csr' % key_alias)
    sys_command = 'keytool -certreq -alias %s -file %s -keystore %s -storepass %s -keypass %s %s' % (
        key_alias, request_path, keystore_path, password, password, server_dname
    )
    _call(sys_command, title='Generating certificate signing request for %s'% key_alias)

# sign server cert with root cert
    cert_path = path.join(key_folder, '%s.crt' % key_alias)
    sys_command = 'openssl x509 -req -CA %s -CAkey %s -in %s -out %s -days 36500 -CAcreateserial -passin pass:%s' % (root_path, key_path, request_path, cert_path, password)
    _call(sys_command, ignore='Getting CA Private Key', title='Signing certificate for %s with root certificate' % key_alias)

# add root cert to server keystore
    root_root, root_node = path.split(root_path)
    root_alias, root_ext = path.splitext(root_node)
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (keystore_path, root_alias, root_path, password, password)
    _call(sys_command, ignore='Certificate was added to keystore', title='Adding root certificate to keystore for %s' % key_alias)

# add server cert to server keystore
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (keystore_path, key_alias, cert_path, password, password)
    _call(sys_command, ignore='Certificate reply was installed in keystore', title='Adding certificate for %s to keystore for %s' % (key_alias, key_alias))

# add root certificate to truststore
    if not truststore_copy:
        if path.exists(truststore_path):
            remove(truststore_path)
        sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (truststore_path, root_alias, root_path, password, password)
        _call(sys_command, ignore='Certificate was added to keystore', title='Generating truststore for root certificate')

# add server cert to truststore
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (truststore_path, key_alias, cert_path, password, password)
    _call(sys_command, ignore='Certificate was added to keystore', title='Adding certificate for %s to truststore' % key_alias)

# remove .srl files
    from os import listdir
    for file_name in listdir('./'):
        if file_name == '.srl':
            remove(file_name)
    for file_name in listdir(key_folder):
        file_alias, file_ext = path.splitext(file_name)
        if file_ext == '.srl':
            remove(path.join(key_folder, file_name))

    return True
486696
private CloseableHttpClient buildClient(boolean trustSelfSigned) {
		try {
			// if required, define custom SSL context allowing self-signed certs
			SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault()
				: SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

			// set timeouts for the HTTP client
			int globalTimeout = readFromProperty("bdTimeout", 100000);
			int connectTimeout = readFromProperty("bdConnectTimeout", globalTimeout);
			int connectionRequestTimeout = readFromProperty("bdConnectionRequestTimeout", globalTimeout);
			int socketTimeout = readFromProperty("bdSocketTimeout", globalTimeout);
			RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(connectTimeout)
				.setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();

			// configure caching
			CacheConfig cacheConfig = CacheConfig.copy(CacheConfig.DEFAULT).setSharedCache(false).setMaxCacheEntries(1000)
				.setMaxObjectSize(2 * 1024 * 1024).build();

			// configure connection pooling
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(RegistryBuilder
				.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory())
				.register("https", new SSLConnectionSocketFactory(sslContext)).build());
			int connectionLimit = readFromProperty("bdMaxConnections", 40);
			// there's only one server to connect to, so max per route matters
			connManager.setMaxTotal(connectionLimit);
			connManager.setDefaultMaxPerRoute(connectionLimit);

			// create the HTTP client
			return CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig)
				.setConnectionManager(connManager).build();
		} catch (GeneralSecurityException e) {
			throw new InternalConfigurationException("Failed to set up SSL context", e);
		}
	}
253812
def _create_ssh_keys(self):
        
        ret, _, _ = utils.run_command(
            [
                'ssh-keygen',
                '-t',
                'rsa',
                '-m',
                'PEM',
                '-N',
                '',
                '-f',
                self.paths.ssh_id_rsa(),
            ]
        )
        if ret != 0:
            raise RuntimeError(
                'Failed to crate ssh keys at %s',
                self.paths.ssh_id_rsa(),
            )
1102261
def create_ssl_context():
        """"""
        ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        ssl_context.check_hostname = False
        ssl_context.verify_mode = ssl.CERT_NONE
        return ssl_context
1101672
def createClientCertificate(self, name, noPass = True, keyLength = 2048, days = 375):
        
        if not name:
            raise ValueError('Require name')
        configPath, keyPath, csrPath, certPath = \
                os.path.join(self.basePath, self.FILE_CONFIG), \
                os.path.join(self.basePath, self.DIR_PRIVATE, '%s.key.pem' % name), \
                os.path.join(self.basePath, self.DIR_CSR, '%s.csr.pem' % name), \
                os.path.join(self.basePath, self.DIR_CERTS, '%s.cert.pem' % name)
        if os.path.isfile(keyPath):
            raise ValueError('Key file exists at [%s]' % keyPath)
        if os.path.isfile(csrPath):
            raise ValueError('CSR file exists at [%s]' % csrPath)
        if os.path.isfile(certPath):
            raise ValueError('Certificate file exists at [%s]' % certPath)
        # Generate the key
        if subprocess.call([ 'openssl', 'genrsa', '-aes256', '-out', keyPath, str(keyLength) ] if not noPass else [ 'openssl', 'genrsa', '-out', keyPath, str(keyLength) ]) != 0:
            raise ValueError('Failed to create key')
        # Generate the csr
        if subprocess.call([ 'openssl', 'req', '-config', configPath, '-key', keyPath, '-new', '-sha256', '-out', csrPath ]) != 0:
            raise ValueError('Failed to create CSR')
        # Generate the certificate
        if subprocess.call([ 'openssl', 'ca', '-config', configPath, '-extensions', 'usr_cert', '-days', str(days), '-notext', '-md', 'sha256', '-in', csrPath, '-out', certPath ]) != 0:
            raise ValueError('Failed to create certificate')
575597
def _sslobj(sock):
    
    pass
    if isinstance(sock._sslobj, _ssl._SSLSocket):
        return sock._sslobj
    else:
        return sock._sslobj._sslobj
376502
static public function generate()
    {
        if (! extension_loaded('openssl')) {
            throw new \RuntimeException("Can only generate a remote desktop certificate when OpenSSL PHP extension is installed.");
        }
        
        // Generate a new private (and public) key pair
        $config = array(
            'config' => __DIR__ . '/../Resources/config/openssl.cnf'
        );
        $privkey = openssl_pkey_new($config);
        
        // Generate a certificate signing request
        $dn = array(
            "commonName" => "AzureDistributionBundle for Symfony Tools"
        );
        $csr = openssl_csr_new($dn, $privkey, $config);
        $sscert = openssl_csr_sign($csr, null, $privkey, 365, $config);
        
        return new self($privkey, $sscert);
    }
270704
public SSLSocketFactory createSslSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{this}, null);
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new AssertionError(e);
        }
    }
1008285
def generate_certificate(common_name, size=DEFAULT_KEY_SIZE):
    '''
        
    '''

    private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
    certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(certificate_path):
        print 'Create {}'.format(certificate_path)
        cmd = 'openssl req -x509 -nodes -newkey rsa:{size} -keyout {private_key_path} -out {certificate_path} -days 3650 -subj "/CN={common_name}"'.format(
            size=size, private_key_path=private_key_path,
            certificate_path=certificate_path, common_name=common_name)
        p = subprocess.Popen(cmd,
                             shell=True,
                             stdout=subprocess.PIPE,
                             close_fds=True)
        p.communicate()
        helpers.file_rights(private_key_path, mode=0400, uid=0, gid=0)
        helpers.file_rights(certificate_path, mode=0444, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(certificate_path)

    clean_links()
    make_links(common_name)
687052
def _create_socket(self):
        
        log.warning('No certificate check is performed for SSL connections')
        s = super(SSL, self)._create_socket()
        return wrap_socket(s)
117823
def create_primary(user_id, pubkey, signer_func, secret_bytes=b''):
    """"""
    pubkey_packet = protocol.packet(tag=(5 if secret_bytes else 6),
                                    blob=(pubkey.data() + secret_bytes))
    user_id_bytes = user_id.encode('utf-8')
    user_id_packet = protocol.packet(tag=13, blob=user_id_bytes)
    data_to_sign = (pubkey.data_to_hash() + user_id_packet[:1] +
                    util.prefix_len('>L', user_id_bytes))
    hashed_subpackets = [
        protocol.subpacket_time(pubkey.created),  # signature time
        # https://tools.ietf.org/html/rfc4880#section-5.2.3.7
        protocol.subpacket_byte(0x0B, 9),  # preferred symmetric algo (AES-256)
        # https://tools.ietf.org/html/rfc4880#section-5.2.3.4
        protocol.subpacket_byte(0x1B, 1 | 2),  # key flags (certify & sign)
        # https://tools.ietf.org/html/rfc4880#section-5.2.3.21
        protocol.subpacket_bytes(0x15, [8, 9, 10]),  # preferred hash
        # https://tools.ietf.org/html/rfc4880#section-5.2.3.8
        protocol.subpacket_bytes(0x16, [2, 3, 1]),  # preferred compression
        # https://tools.ietf.org/html/rfc4880#section-5.2.3.9
        protocol.subpacket_byte(0x17, 0x80),  # key server prefs (no-modify)
        # https://tools.ietf.org/html/rfc4880#section-5.2.3.17
        protocol.subpacket_byte(0x1E, 0x01),  # advanced features (MDC)
        # https://tools.ietf.org/html/rfc4880#section-5.2.3.24
    ]
    unhashed_subpackets = [
        protocol.subpacket(16, pubkey.key_id()),  # issuer key id
        protocol.CUSTOM_SUBPACKET]

    signature = protocol.make_signature(
        signer_func=signer_func,
        public_algo=pubkey.algo_id,
        data_to_sign=data_to_sign,
        sig_type=0x13,  # user id & public key
        hashed_subpackets=hashed_subpackets,
        unhashed_subpackets=unhashed_subpackets)

    sign_packet = protocol.packet(tag=2, blob=signature)
    return pubkey_packet + user_id_packet + sign_packet
216077
private SSLContext buildSSLContext() {
        String keyANDkeystorePassword = configuration.getSslKeyPassword() == null ? configuration.getSslPassword() : configuration.getSslKeyPassword();
        return buildSSLContext(configuration.getSslKeystore(), configuration.getSslKeystoreType(),
                keyANDkeystorePassword, keyANDkeystorePassword,
                configuration.getSslKeyAlias(),
                configuration.getTrustStore(), configuration.getTrustStoreType(),
                configuration.getTrustStorePassword(),
                configuration.isValidateCerts(), configuration.getCrlPath(),
                null,
                configuration.isValidatePeerCerts(), configuration.isEnableCRLDP(), configuration.isEnableOCSP(),
                configuration.getOcspResponderURL(),
                configuration.getSslKeystoreProvider(),
                configuration.getSslTrustStoreProvider(),
                configuration.getSslProvider());
    }
953152
def create_and_write_saml_metadata(proxy_conf, key, cert, dir, valid, split_frontend_metadata=False,
                                   split_backend_metadata=False):
    
    satosa_config = SATOSAConfig(proxy_conf)
    secc = _get_security_context(key, cert)
    frontend_entities, backend_entities = create_entity_descriptors(satosa_config)

    output = []
    if frontend_entities:
        if split_frontend_metadata:
            output.extend(_create_split_entity_descriptors(frontend_entities, secc, valid))
        else:
            output.extend(_create_merged_entities_descriptors(frontend_entities, secc, valid, "frontend.xml"))
    if backend_entities:
        if split_backend_metadata:
            output.extend(_create_split_entity_descriptors(backend_entities, secc, valid))
        else:
            output.extend(_create_merged_entities_descriptors(backend_entities, secc, valid, "backend.xml"))

    for metadata, filename in output:
        path = os.path.join(dir, filename)
        print("Writing metadata to '{}'".format(path))
        with open(path, "w") as f:
            f.write(metadata)