Example usage for javax.net.ssl TrustManagerFactory getDefaultAlgorithm

List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory getDefaultAlgorithm.

Prototype

public static final String getDefaultAlgorithm() 

Source Link

Document

Obtains the default TrustManagerFactory algorithm name.

Usage

From source file:org.wso2.carbon.identity.core.util.ClientAuthX509TrustManager.java

/**
 * This method reloads the TrustManager by reading the carbon server's default trust store file
 *
 * @throws Exception/* w  w  w. j a v a 2s .  co  m*/
 */
private void setupTrustManager() throws Exception {

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore clientTrustStore;
    try (InputStream trustStoreInputStream = new FileInputStream(TRUST_STORE_LOCATION)) {

        clientTrustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
        clientTrustStore.load(trustStoreInputStream, null);

        trustManagerFactory.init(clientTrustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        for (TrustManager t : trustManagers) {
            if (t instanceof X509TrustManager) {
                trustManager = (X509TrustManager) t;
                System.setProperty(PROP_TRUST_STORE_UPDATE_REQUIRED, Boolean.FALSE.toString());
                return;
            }
        }
        throw new IdentityException("No X509TrustManager in TrustManagerFactory");
    }
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

/**
 * Loads the CA certificate into an in-memory keystore and creates an {@link SSLSocketFactory}.
 *
 * @return SSLSocketFactory/*from   w w w .  java  2 s . c o m*/
 */
public SSLSocketFactory getPinnedSSLSocketFactory() {
    InputStream caCertInputStream = null;
    InputStream clientKeyPair = null;
    try {
        // Load the CA certificate into memory
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caCertInputStream = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslCaCert());
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        // Load the CA certificate into the trusted KeyStore
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        // Create a TrustManagerFactory with the trusted KeyStore
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // Load the client certificate and private key into another KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        clientKeyPair = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslClientKeyStore());
        keyStore.load(clientKeyPair,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Create a TrustManagerFactory with the client key pair KeyStore
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Initialize the SSLContext and return an SSLSocketFactory;
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        return sc.getSocketFactory();
    } catch (CertificateException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException
            | IOException | KeyManagementException e) {
        throw new RuntimeException("The KeyStore for contacting the Companion Service could not be loaded.", e);
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
        IOUtils.closeQuietly(clientKeyPair);
    }
}

From source file:org.apache.qpid.systest.rest.RestTestHelper.java

public HttpURLConnection openManagementConnection(String path, String method) throws IOException {
    URL url = getManagementURL(path);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    if (_useSsl) {
        try {//w  w w  . java2 s. c o  m
            // We have to use a SSLSocketFactory from a new SSLContext so that we don't re-use
            // the JVM's defaults that may have been initialised in previous tests.

            SSLContext sslContext = SSLContextFactory.buildClientContext(TRUSTSTORE, TRUSTSTORE_PASSWORD,
                    KeyStore.getDefaultType(), TrustManagerFactory.getDefaultAlgorithm(), null, null, null,
                    null, null);

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            ((HttpsURLConnection) httpCon).setSSLSocketFactory(sslSocketFactory);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    if (_username != null) {
        String encoded = new String(new Base64().encode((_username + ":" + _password).getBytes()));
        httpCon.setRequestProperty("Authorization", "Basic " + encoded);
    }

    httpCon.setDoOutput(true);
    httpCon.setRequestMethod(method);
    return httpCon;
}

From source file:gov.nist.toolkit.soap.axis2.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from  ww  w. j a  v  a2  s  .c o m*/
    LOG.debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();

    LOG.debug("Found " + trustmanagers.length + " trust managers");

    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        } else {
            System.out.println("non 509 trust manager: class is " + trustmanagers[i].getClass().getName());
        }
    }
    return trustmanagers;
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

private TrustManagerFactory getTrustManagerFactory(final KeyStore keystore)
        throws KeyStoreException, IOException {
    try {/*from  w  w w .  j a v  a 2  s. c om*/
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keystore);
        return trustManagerFactory;
    } catch (NoSuchAlgorithmException e) {
        // no support for algorithm, if this happens we're kind of screwed
        // we're using the default so it should never happen
        log.error("The algorithm is not supported. Error message:" + e.getMessage());
        throw new KeyStoreException(e);
    }
}

From source file:org.wso2.carbon.identity.core.util.DynamicX509TrustManager.java

/**
 * This method reloads the TrustManager by reading the carbon server's default trust store file
 *
 * @throws Exception/* w  w  w  . ja v  a  2s  .  c  om*/
 */
private void setupTrustManager() throws Exception {

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore clientTrustStore = null;
    try (InputStream trustStoreInputStream = new FileInputStream(TRUST_STORE_LOCATION)) {

        clientTrustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
        clientTrustStore.load(trustStoreInputStream, null);
        trustManagerFactory.init(clientTrustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        for (TrustManager t : trustManagers) {
            if (t instanceof X509TrustManager) {
                trustManager = (X509TrustManager) t;
                System.setProperty(IdentityUtil.PROP_TRUST_STORE_UPDATE_REQUIRED, Boolean.FALSE.toString());
                return;
            }
        }
        throw new IdentityException("No X509TrustManager in TrustManagerFactory");
    }
}

From source file:org.appenders.log4j2.elasticsearch.jest.PEMCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder builder) {

    if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }//  w  w  w.  ja v a2  s  .  com

    try (FileInputStream clientCert = new FileInputStream(new File(clientCertPath));
            FileInputStream key = new FileInputStream(new File(keyPath));
            FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))) {
        KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase));
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyPassphrase.toCharArray());

        KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies);

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

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        builder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        builder.httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }

}

From source file:org.xdi.net.SslDefaultHttpClient.java

private TrustManager[] getTrustManagers() throws Exception {
    KeyStore keyStore = getKeyStore(this.trustStoreType, this.trustStorePath, this.trustStorePassword);

    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmFactory.init(keyStore);/*from w w w .  j a  va 2  s. co  m*/

    return tmFactory.getTrustManagers();
}

From source file:de.metas.procurement.webui.ActiveMQBrokerConfiguration.java

/**
 * @return embedded ActiveMQ broker or <code>null</code>
 *//*  w  ww  . j  ava  2 s .c  om*/
@Bean
public BrokerService brokerService() throws Exception {
    if (!runEmbeddedBroker) {
        logger.info("Skip creating an ActiveMQ broker service");
        return null;
    }

    final BrokerService brokerService = new BrokerService();

    if (useSSL) {
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore keystore = KeyStore.getInstance("JKS");
            final Resource keyStoreResource = Application.getContext().getResource(keyStoreFileResourceURL);
            final InputStream keyStoreStream = keyStoreResource.getInputStream();
            keystore.load(keyStoreStream, keyStorePassword.toCharArray());

            kmf.init(keystore, keyStorePassword.toCharArray());
        }

        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore trustStore = KeyStore.getInstance("JKS");
            final Resource trustStoreResource = Application.getContext().getResource(trustStoreFileResourceURL);
            final InputStream trustStoreStream = trustStoreResource.getInputStream();
            trustStore.load(trustStoreStream, trustStorePassword.toCharArray());

            tmf.init(trustStore);
        }

        final SslContext sslContext = new SslContext(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        brokerService.setSslContext(sslContext);
    }

    //
    // "client" Connector
    {
        final TransportConnector connector = new TransportConnector();
        connector.setUri(new URI(brokerUrl.trim()));
        brokerService.addConnector(connector);
    }

    //
    // "Network of brokers" connector
    if (isSet(networkConnector_discoveryAddress)) {
        final DiscoveryNetworkConnector discoveryNetworkConnector = new DiscoveryNetworkConnector(
                new URI(networkConnector_discoveryAddress.trim()));
        discoveryNetworkConnector.setDuplex(true); // without this, we can send to the other broker, but won't get reposnses

        if (isSet(networkConnector_userName)) {
            discoveryNetworkConnector.setUserName(networkConnector_userName.trim());
        }
        if (isSet(networkConnector_password)) {
            discoveryNetworkConnector.setPassword(networkConnector_password.trim());
        }

        // we need to set ConduitSubscriptions to false,
        // see section "Conduit subscriptions and consumer selectors" on http://activemq.apache.org/networks-of-brokers.html
        discoveryNetworkConnector.setConduitSubscriptions(false);

        logger.info("Adding network connector: {}", networkConnector_discoveryAddress);
        brokerService.addNetworkConnector(discoveryNetworkConnector);
    }

    brokerService.setBrokerName(embeddedBrokerName);
    brokerService.start();
    logger.info("Embedded JMS broker started on URL " + brokerUrl);
    return brokerService;
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public void initialize(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    onSharedPreferenceChanged(settings, null);

    settings.registerOnSharedPreferenceChangeListener(this);

    try {//from  w w w.ja v  a 2  s.c  om
        KeyStore keystoreCA = KeyStore.getInstance(KEYSTORE_TYPE);
        keystoreCA.load(context.getResources().openRawResource(R.raw.keystore), PWD);

        KeyStore keystoreClient = null;

        File file = context.getFileStreamPath(KEYSTORE_CLIENT_FILENAME);

        if (file.exists()) {
            keystoreClient = KeyStore.getInstance(KEYSTORE_TYPE);
            InputStream in = new FileInputStream(file);
            keystoreClient.load(in, PWD);
        }

        ready = keystoreClient != null && keystoreClient.getKey(MDM_CLIENT_CERT_ALIAS, PWD) != null;

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystoreCA);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(keystoreClient, PWD);

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "load keystore error", e);
    }
}