Example usage for javax.net.ssl KeyManagerFactory getKeyManagers

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

Introduction

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

Prototype

public final KeyManager[] getKeyManagers() 

Source Link

Document

Returns one key manager for each type of key material.

Usage

From source file:org.apache.activemq.ActiveMQSslConnectionFactoryTest.java

public static KeyManager[] getKeyManager() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore ks = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE);
    KeyManager[] keystoreManagers = null;

    byte[] sslCert = loadClientCredential(ActiveMQSslConnectionFactoryTest.SERVER_KEYSTORE);

    if (sslCert != null && sslCert.length > 0) {
        ByteArrayInputStream bin = new ByteArrayInputStream(sslCert);
        ks.load(bin, ActiveMQSslConnectionFactoryTest.PASSWORD.toCharArray());
        kmf.init(ks, ActiveMQSslConnectionFactoryTest.PASSWORD.toCharArray());
        keystoreManagers = kmf.getKeyManagers();
    }//from ww  w. ja v a2s. co  m
    return keystoreManagers;
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Same as buildContext(), but wraps all X509TrustManagers in a SavableTrustManager to provide
 * UntrustedCertificateExceptions so that when a client connects to a server it does not trust,
 * the program can recover the key and ask the user if they wish to trust it.
 *
 * @param trustMaterial//from  ww w . j a  va 2 s.  com
 * @return
 */
public static SSLContext buildClientContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);
        ctx = SSLContext.getInstance("TLS");
        //key manager factory go!
        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

        TrustManager[] trustManagers = tmf.getTrustManagers();

        for (int i = 0; i < trustManagers.length; i++) {
            if (trustManagers[i] instanceof X509TrustManager) {
                System.out.println("Wrapped a trust manager.");
                trustManagers[i] = new SavableTrustManager((X509TrustManager) trustManagers[i]);
            }
        }

        ctx.init(keyMgr.getKeyManagers(), trustManagers, null);
    } catch (KeyStoreException | UnrecoverableKeyException | KeyManagementException
            | NoSuchAlgorithmException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ctx = null;
    }

    return ctx;
}

From source file:org.apache.ranger.services.nifi.client.NiFiConnectionMgr.java

private static SSLContext createSslContext(final String keystore, final char[] keystorePasswd,
        final String keystoreType, final String truststore, final char[] truststorePasswd,
        final String truststoreType, final String protocol) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }/*from   www  .  java 2  s. co m*/
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePasswd);

    // prepare the truststore
    final KeyStore trustStore = KeyStore.getInstance(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java

/**
 * Create basic SSL connection factory//from  w ww .  j a  v a2 s .  c o m
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {

                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:orca.ektorp.client.ContextualSSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keystorePassword, final KeyStore truststore, final SecureRandom random,
        final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;//from ww  w.ja  v  a  2 s.c  o  m
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null);
    KeyManager[] keymanagers = kmfactory.getKeyManagers();
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(truststore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    if (trustmanagers != null && trustStrategy != null) {
        for (int i = 0; i < trustmanagers.length; i++) {
            TrustManager tm = trustmanagers[i];
            /*
             * @TODO: I need to uncomment the 3 lines below. TrustManagerDecorator is not public (package visibility)
             */
            // if (tm instanceof X509TrustManager) {
            //    trustmanagers[i] = new TrustManagerDecorator(
            //            (X509TrustManager) tm, trustStrategy);
            //}
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keymanagers, trustmanagers, random);
    return sslcontext;
}

From source file:org.apache.nifi.framework.security.util.SslContextFactory.java

public static SSLContext createSslContext(final NiFiProperties props, final boolean strict)
        throws SslContextCreationException {

    final boolean hasKeystoreProperties = hasKeystoreProperties(props);
    if (hasKeystoreProperties == false) {
        if (strict) {
            throw new SslContextCreationException(
                    "SSL context cannot be created because keystore properties have not been configured.");
        } else {//from w  w w .  j a va 2  s. co  m
            return null;
        }
    } else if (props.getNeedClientAuth() && hasTruststoreProperties(props) == false) {
        throw new SslContextCreationException(
                "Need client auth is set to 'true', but no truststore properties are configured.");
    }

    try {
        // prepare the trust store
        final KeyStore trustStore;
        if (hasTruststoreProperties(props)) {
            trustStore = KeyStoreUtils
                    .getTrustStore(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE));
            try (final InputStream trustStoreStream = new FileInputStream(
                    props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
                trustStore.load(trustStoreStream,
                        props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD).toCharArray());
            }
        } else {
            trustStore = null;
        }
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // prepare the key store
        final KeyStore keyStore = KeyStoreUtils
                .getKeyStore(props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE));
        try (final InputStream keyStoreStream = new FileInputStream(
                props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
            keyStore.load(keyStoreStream,
                    props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray());
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        // if the key password is provided, try to use that - otherwise default to the keystore password
        if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD))) {
            keyManagerFactory.init(keyStore,
                    props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore,
                    props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray());
        }

        // initialize the ssl context
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        sslContext.getDefaultSSLParameters().setNeedClientAuth(props.getNeedClientAuth());

        return sslContext;

    } catch (final KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | UnrecoverableKeyException | KeyManagementException e) {
        throw new SslContextCreationException(e);
    }
}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception {

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    keyStore.load(null, null);//from   w  w  w  . java 2  s  .  c om

    for (SyncAccount syncAccount : SyncAccountService.findAll()) {
        if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) {
            continue;
        }

        try {
            PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey());

            if (privateKey == null) {
                _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId());

                continue;
            }

            X509Certificate x509Certificate = LanPEMParserUtil
                    .parseX509Certificate(syncAccount.getLanCertificate());

            if (x509Certificate == null) {
                _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId());

                continue;
            }

            keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate);

            keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(),
                    new Certificate[] { x509Certificate });
        } catch (Exception e) {
            _logger.error(e.getMessage(), e);
        }
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(keyStore);

    SSLContext sslContext = SSLContext.getInstance("TLS");

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

From source file:io.wcm.caravan.commons.httpclient.impl.helpers.CertificateLoader.java

/**
 * Build SSL Socket factory.//  w w w . j ava2 s.  co m
 * @param config Http client configuration
 * @return SSL socket factory.
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static SSLContext buildSSLContext(HttpClientConfig config) throws IOException, GeneralSecurityException {

    KeyManagerFactory kmf = null;
    if (isSslKeyManagerEnabled(config)) {
        kmf = getKeyManagerFactory(config.getKeyStorePath(), new StoreProperties(config.getKeyStorePassword(),
                config.getKeyManagerType(), config.getKeyStoreType()));
    }
    TrustManagerFactory tmf = null;
    if (isSslTrustStoreEnbaled(config)) {
        StoreProperties storeProperties = new StoreProperties(config.getTrustStorePassword(),
                config.getTrustManagerType(), config.getTrustStoreType());
        tmf = getTrustManagerFactory(config.getTrustStorePath(), storeProperties);
    }

    SSLContext sslContext = SSLContext.getInstance(config.getSslContextType());
    sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null,
            null);

    return sslContext;
}

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  .j  ava  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  av  a2  s  . co  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;
}