Example usage for javax.net.ssl KeyManagerFactory init

List of usage examples for javax.net.ssl KeyManagerFactory init

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory init.

Prototype

public final void init(KeyStore ks, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Initializes this factory with a source of key material.

Usage

From source file:com.vmware.photon.controller.core.Main.java

private static PhotonControllerXenonHost startXenonHost(PhotonControllerConfig photonControllerConfig,
        ThriftModule thriftModule, DeployerConfig deployerConfig, SSLContext sslContext) throws Throwable {
    // Values for CloudStore
    final HostClientFactory hostClientFactory = thriftModule.getHostClientFactory();
    final AgentControlClientFactory agentControlClientFactory = thriftModule.getAgentControlClientFactory();
    final NsxClientFactory nsxClientFactory = new NsxClientFactory();

    // Values for Scheduler
    final ServerSet cloudStoreServerSet = new StaticServerSet(
            new InetSocketAddress(photonControllerConfig.getXenonConfig().getRegistrationAddress(),
                    Constants.PHOTON_CONTROLLER_PORT));
    final CloudStoreHelper cloudStoreHelper = new CloudStoreHelper(cloudStoreServerSet);

    final CloseableHttpAsyncClient httpClient;
    try {/*from w w w . ja  va  2  s .co  m*/
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial((chain, authtype) -> true).build();
        httpClient = HttpAsyncClientBuilder.create()
                .setHostnameVerifier(SSLIOSessionStrategy.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslcontext)
                .build();
        httpClient.start();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    ServerSet apiFeServerSet = new StaticServerSet(new InetSocketAddress(
            photonControllerConfig.getXenonConfig().getRegistrationAddress(), Constants.MANAGEMENT_API_PORT));

    logger.info("Creating PhotonController Xenon Host");
    final PhotonControllerXenonHost photonControllerXenonHost = new PhotonControllerXenonHost(
            photonControllerConfig.getXenonConfig(), hostClientFactory, agentControlClientFactory,
            nsxClientFactory, cloudStoreHelper, sslContext);
    logger.info("Created PhotonController Xenon Host");

    // Set referer Uri from the xenon host, because we do not want to rely on
    // CloudStoreHelper's default mechanise to create referer based on local address,
    // because CloudStoreHelper uses InetAddress.getLocalHost() which depends on
    // /etc/hosts having a hostname entry, which is not always available.
    // This change will allow people to run this service without need to
    // update their /etc/hosts file.
    cloudStoreHelper.setRefererUri(photonControllerXenonHost.getUri());

    final ConstraintChecker checker = new CloudStoreConstraintChecker(cloudStoreHelper,
            photonControllerXenonHost);

    logger.info("Creating Cloud Store Xenon Service Group");
    CloudStoreServiceGroup cloudStoreServiceGroup = createCloudStoreServiceGroup(deployerConfig.isInstaller());
    logger.info("Created Cloud Store Xenon Service Group");

    logger.info("Registering Cloud Store Xenon Service Group");
    photonControllerXenonHost.registerCloudStore(cloudStoreServiceGroup);
    logger.info("Registered Cloud Store Xenon Service Group");

    logger.info("Creating Scheduler Xenon Service Group");
    SchedulerServiceGroup schedulerServiceGroup = createSchedulerServiceGroup(photonControllerConfig.getRoot(),
            checker);
    logger.info("Created Scheduler Xenon Service Group");

    logger.info("Registering Scheduler Xenon Service Group");
    photonControllerXenonHost.registerScheduler(schedulerServiceGroup);
    logger.info("Registered Scheduler Xenon Service Group");

    logger.info("Creating Housekeeper Xenon Service Group");
    HousekeeperServiceGroup housekeeperServiceGroup = createHousekeeperServiceGroup();
    logger.info("Created Housekeeper Xenon Service Group");

    logger.info("Registering Housekeeper Xenon Service Group");
    photonControllerXenonHost.registerHousekeeper(housekeeperServiceGroup);
    logger.info("Registered Housekeeper Xenon Service Group");

    logger.info("Creating Deployer Xenon Service Group");
    DeployerServiceGroup deployerServiceGroup = createDeployerServiceGroup(photonControllerConfig,
            deployerConfig, apiFeServerSet, cloudStoreServerSet, httpClient);
    logger.info("Created Deployer Xenon Service Group");

    logger.info("Registering Deployer Xenon Service Group");
    photonControllerXenonHost.registerDeployer(deployerServiceGroup);
    logger.info("Registered Deployer Xenon Service Group");

    DeployerContext deployerContext = deployerConfig.getDeployerContext();
    if (deployerContext.isAuthEnabled()) {
        ServiceClient serviceClient = NettyHttpServiceClient.create(Main.class.getSimpleName(),
                Executors.newFixedThreadPool(Utils.DEFAULT_THREAD_COUNT),
                Executors.newScheduledThreadPool(Utils.DEFAULT_IO_THREAD_COUNT), photonControllerXenonHost);

        /*
        To make sure that Xenon uses only TLSv1.2 and disallows SSLv3, TLSv1,
        TLSv1.1 the Docker file for the photon-controller-core container is edited.
        The java.security file located inside the container at the location
        /var/opt/OpenJDK-* /jre/lib/security has the information under the
        jdk.tls.disabledAlgorithms
        */

        SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance("JKS");
        try (FileInputStream fis = new FileInputStream(deployerContext.getKeyStorePath())) {
            keyStore.load(fis, deployerContext.getKeyStorePassword().toCharArray());
        }
        keyManagerFactory.init(keyStore, deployerContext.getKeyStorePassword().toCharArray());
        clientContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        serviceClient.setSSLContext(clientContext);
        photonControllerXenonHost.setClient(serviceClient);
    }

    logger.info("Starting PhotonController Xenon Host");
    photonControllerXenonHost.start();
    logger.info("Started PhotonController Xenon Host");

    logger.info("Creating SystemConfig instance");
    SystemConfig.createInstance(photonControllerXenonHost);
    logger.info("Created SystemConfig instance");
    return photonControllerXenonHost;
}

From source file:org.lealone.cluster.security.SSLFactory.java

public static SSLContext createSSLContext(EncryptionOptions options, boolean buildTruststore)
        throws IOException {
    FileInputStream tsf = null;/*from  w w  w. j a  v  a 2  s  .  c o  m*/
    FileInputStream ksf = null;
    SSLContext ctx;
    try {
        ctx = SSLContext.getInstance(options.protocol);
        TrustManager[] trustManagers = null;

        if (buildTruststore) {
            tsf = new FileInputStream(options.truststore);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(options.algorithm);
            KeyStore ts = KeyStore.getInstance(options.store_type);
            ts.load(tsf, options.truststore_password.toCharArray());
            tmf.init(ts);
            trustManagers = tmf.getTrustManagers();
        }

        ksf = new FileInputStream(options.keystore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(options.algorithm);
        KeyStore ks = KeyStore.getInstance(options.store_type);
        ks.load(ksf, options.keystore_password.toCharArray());
        if (!checkedExpiry) {
            for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
                String alias = aliases.nextElement();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    Date expires = ((X509Certificate) ks.getCertificate(alias)).getNotAfter();
                    if (expires.before(new Date()))
                        logger.warn("Certificate for {} expired on {}", alias, expires);
                }
            }
            checkedExpiry = true;
        }
        kmf.init(ks, options.keystore_password.toCharArray());

        ctx.init(kmf.getKeyManagers(), trustManagers, null);

    } catch (Exception e) {
        throw new IOException("Error creating the initializing the SSL Context", e);
    } finally {
        FileUtils.closeQuietly(tsf);
        FileUtils.closeQuietly(ksf);
    }
    return ctx;
}

From source file:org.apache.cassandra.security.SSLFactory.java

@SuppressWarnings("resource")
public static SSLContext createSSLContext(EncryptionOptions options, boolean buildTruststore)
        throws IOException {
    FileInputStream tsf = null;/*from   www  . j a va2 s . c o  m*/
    FileInputStream ksf = null;
    SSLContext ctx;
    try {
        ctx = SSLContext.getInstance(options.protocol);
        TrustManager[] trustManagers = null;

        if (buildTruststore) {
            tsf = new FileInputStream(options.truststore);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(options.algorithm);
            KeyStore ts = KeyStore.getInstance(options.store_type);
            ts.load(tsf, options.truststore_password.toCharArray());
            tmf.init(ts);
            trustManagers = tmf.getTrustManagers();
        }

        ksf = new FileInputStream(options.keystore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(options.algorithm);
        KeyStore ks = KeyStore.getInstance(options.store_type);
        ks.load(ksf, options.keystore_password.toCharArray());
        if (!checkedExpiry) {
            for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
                String alias = aliases.nextElement();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    Date expires = ((X509Certificate) ks.getCertificate(alias)).getNotAfter();
                    if (expires.before(new Date()))
                        logger.warn("Certificate for {} expired on {}", alias, expires);
                }
            }
            checkedExpiry = true;
        }
        kmf.init(ks, options.keystore_password.toCharArray());

        ctx.init(kmf.getKeyManagers(), trustManagers, null);

    } catch (Exception e) {
        throw new IOException("Error creating the initializing the SSL Context", e);
    } finally {
        FileUtils.closeQuietly(tsf);
        FileUtils.closeQuietly(ksf);
    }
    return ctx;
}

From source file:com.ibm.iotf.client.AbstractClient.java

static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
        final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate caCert = null;

    if (caCrtFile != null) {
        // load CA certificate
        PEMReader reader = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
        caCert = (X509Certificate) reader.readObject();
        reader.close();//from   www  .j  a v  a 2 s.  c  o m
    } else {
        ClassLoader classLoader = AbstractClient.class.getClassLoader();
        PEMReader reader = new PEMReader(
                new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream()));
        caCert = (X509Certificate) reader.readObject();
        reader.close();
    }

    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    TrustManagerFactory tmf = null;
    if (caCert != null) {
        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance("JKS");
        //caKs.load(null, null);
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
    }
    // client key and certificates are sent to server so it can authenticate us
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, password.toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    if (tmf != null) {
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        context.init(kmf.getKeyManagers(), null, null);
    }

    return context.getSocketFactory();
}

From source file:com.fanmei.pay4j.http.WeixinSSLRequestExecutor.java

public WeixinSSLRequestExecutor(WeixinConfig weixinConfig) throws WeixinException {
    InputStream inputStream = this.getClass().getClassLoader()
            .getResourceAsStream(weixinConfig.getCertificateFile());
    try {//from  w  ww. j a  v  a2 s. c  o m
        String password = weixinConfig.getAccount().getCertificateKey();
        KeyStore keyStore = KeyStore.getInstance(Constants.PKCS12);
        keyStore.load(inputStream, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(Constants.SunX509);
        kmf.init(keyStore, password.toCharArray());
        SSLContext sslContext = SSLContext.getInstance(Constants.TLS);
        sslContext.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        throw WeixinException.of("Key load error", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {

            }
        }
    }
}

From source file:org.apache.ftpserver.ssl.MinaClientAuthTest.java

protected FTPSClient createFTPClient() throws Exception {
    FTPSClient client = new FTPSClient(useImplicit());
    client.setNeedClientAuth(true);/*  w  ww  . j  ava  2  s  .com*/

    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = new FileInputStream(FTPCLIENT_KEYSTORE);
    ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
    fis.close();

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, KEYSTORE_PASSWORD.toCharArray());

    client.setKeyManager(kmf.getKeyManagers()[0]);

    return client;
}

From source file:org.wso2.msf4j.conf.SSLHandlerFactory.java

public SSLHandlerFactory(SSLConfig sslConfig) {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }/* www.j  a  v  a 2 s . co  m*/
    try {
        KeyStore ks = getKeyStore(sslConfig.getKeyStore(), sslConfig.getKeyStorePassword());
        // Set up key manager factory to use our key store
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks,
                sslConfig.getCertificatePassword() != null ? sslConfig.getCertificatePassword().toCharArray()
                        : sslConfig.getKeyStorePassword().toCharArray());
        KeyManager[] keyManagers = kmf.getKeyManagers();
        TrustManager[] trustManagers = null;
        if (sslConfig.getTrustKeyStore() != null) {
            this.needClientAuth = true;
            KeyStore tks = getKeyStore(sslConfig.getTrustKeyStore(), sslConfig.getTrustKeyStorePassword());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
            tmf.init(tks);
            trustManagers = tmf.getTrustManagers();
        }
        serverContext = SSLContext.getInstance(protocol);
        serverContext.init(keyManagers, trustManagers, null);
    } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            | IOException e) {
        throw new IllegalArgumentException("Failed to initialize the server-side SSLContext", e);
    }
}

From source file:ddf.security.sts.claimsHandler.ClaimsHandlerManager.java

public static KeyManagerFactory createKeyManagerFactory(String keyStoreLoc, String keyStorePass)
        throws IOException {
    KeyManagerFactory kmf;
    try {/*from w w  w.j  a  v  a2s . c o  m*/
        // keystore stuff
        KeyStore keyStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType"));
        LOGGER.debug("keyStoreLoc = {}", keyStoreLoc);
        FileInputStream keyFIS = new FileInputStream(keyStoreLoc);
        try {
            LOGGER.debug("Loading keyStore");
            keyStore.load(keyFIS, keyStorePass.toCharArray());
        } catch (CertificateException e) {
            throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e);
        } finally {
            IOUtils.closeQuietly(keyFIS);
        }
        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePass.toCharArray());
        LOGGER.debug("key manager factory initialized");
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(
                "Problems creating SSL socket. Usually this is "
                        + "referring to the certificate sent by the server not being trusted by the client.",
                e);
    } catch (UnrecoverableKeyException e) {
        throw new IOException("Unable to load keystore. " + keyStoreLoc, e);
    } catch (KeyStoreException e) {
        throw new IOException("Unable to read keystore. " + keyStoreLoc, e);
    }

    return kmf;
}

From source file:com.thoughtworks.go.security.AuthSSLKeyManagerFactory.java

private KeyManager[] createKeyManagers(KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    bombIfNull(keystore, "Keystore may not be null");

    LOG.trace("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword.toCharArray());
    return kmfactory.getKeyManagers();
}

From source file:com.wudaosoft.net.httpclient.SSLContextBuilder.java

public SSLContext buildPKCS12() {

    Args.notEmpty(password, "password");
    Args.notNull(cert, "cert");

    char[] pwd = password.toCharArray();

    try {//  w ww  .j a  v  a2 s. c  o  m
        KeyStore ks = KeyStore.getInstance("PKCS12");

        ks.load(cert.openStream(), pwd);

        //  & ?
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, pwd);

        //  SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

        return sslContext;
    } catch (Exception e) {
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        throw new RuntimeException(e);
    }
}