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.jboss.as.test.integration.logging.syslogserver.TLSSyslogServer.java

/**
 * Creates custom sslContext from keystore and truststore configured in
 *
 * @see org.productivity.java.syslog4j.server.impl.net.tcp.TCPNetSyslogServer#initialize()
 *///from  w  ww  . j  av a2 s . c  o  m
@Override
public void initialize() throws SyslogRuntimeException {
    super.initialize();

    if (isBouncyCastleInstalled()) {
        removeBouncyCastle();
        addBouncyCastleOnShutdown = true;
    }

    final SSLTCPNetSyslogServerConfigIF config = (SSLTCPNetSyslogServerConfigIF) this.tcpNetSyslogServerConfig;

    try {
        final char[] keystorePwd = config.getKeyStorePassword().toCharArray();
        final KeyStore keystore = loadKeyStore(config.getKeyStore(), keystorePwd);
        final char[] truststorePassword = config.getTrustStorePassword().toCharArray();
        final KeyStore truststore = loadKeyStore(config.getTrustStore(), truststorePassword);

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePwd);

        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
        LOGGER.error("Exception occurred during SSLContext for TLS syslog server initialization", e);
        throw new SyslogRuntimeException(e);
    }
}

From source file:org.wso2.andes.configuration.modules.JKSStore.java

public JKSStore(String rootXPath) throws ConfigurationException {

    String locationXPath = rootXPath + relativeXPathForLocation;
    String passwordXPath = rootXPath + relativeXPathForPassword;
    String storeAlgorithmXPath = rootXPath + relativeXPathForStoreAlgorithm;

    String defaultStoreLocation = null;
    String defaultStoreAlgorithm = null;

    if (StringUtils.containsIgnoreCase(rootXPath, "trustStore")) {
        defaultStoreLocation = JKS_BASE_PATH + "wso2carbon.jks";
        defaultStoreAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    } else {// w ww  .ja v  a 2 s.  c om
        defaultStoreAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        defaultStoreLocation = JKS_BASE_PATH + "client-truststore.jks";
    }

    // After deriving the full xpaths, the AndesConfigurationManager is used to extract the values for each
    // property.
    storeLocation = AndesConfigurationManager.deriveValidConfigurationValue(locationXPath, String.class,
            defaultStoreLocation);
    password = AndesConfigurationManager.deriveValidConfigurationValue(passwordXPath, String.class,
            DEFAULT_STORE_PASSWORD);
    storeAlgorithm = AndesConfigurationManager.deriveValidConfigurationValue(storeAlgorithmXPath, String.class,
            defaultStoreAlgorithm);
}

From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultX509TrustManager.java

public DefaultX509TrustManager(final KeyStore keyStore)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    final TrustManagerFactory factory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(keyStore);//from w  w  w .j a va  2  s.com
    final TrustManager[] trustManagers = factory.getTrustManagers();

    if (trustManagers.length == 0) {
        throw new NoSuchAlgorithmException("No trust manager found"); //$NON-NLS-1$
    }

    if (!(trustManagers[0] instanceof X509TrustManager)) {
        throw new NoSuchAlgorithmException("No X509 trust manager found"); //$NON-NLS-1$
    }

    standardTrustManager = (X509TrustManager) trustManagers[0];
}

From source file:com.alliander.osgp.shared.usermanagement.UserManagementClient.java

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation//  ww  w. jav  a  2 s.  c  om
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the UserManagementClient.
 *
 * @throws UserManagementClientException
 *             In case the construction fails, a
 *             UserManagmentClientException will be thrown.
 */
public UserManagementClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws UserManagementClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers);
        if (this.webClient == null) {
            throw new UserManagementClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new UserManagementClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new UserManagementClientException(CONSTRUCTION_FAILED, exception);
    }
}

From source file:com.alphabetbloc.accessmrs.utilities.MyTrustManager.java

public MyTrustManager(KeyStore localKeyStore) {

    try {// w  w w .  j a v a  2s . c  o m
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);

        defaultTrustManager = findX509TrustManager(tmf);
        if (defaultTrustManager == null) {
            throw new IllegalStateException("Couldn't find X509TrustManager");
        }

        localTrustManager = new LocalStoreX509TrustManager(localKeyStore);

        List<X509Certificate> allIssuers = new ArrayList<X509Certificate>();

        for (X509Certificate cert : localTrustManager.getAcceptedIssuers()) {
            allIssuers.add(cert);
        }
        for (X509Certificate cert : defaultTrustManager.getAcceptedIssuers()) {
            allIssuers.add(cert);
        }
        acceptedIssuers = allIssuers.toArray(new X509Certificate[allIssuers.size()]);
    } catch (GeneralSecurityException e) {
        Log.e(TAG, "We have caught an exception in creating a trust manager!");
        throw new RuntimeException(e);
    }

}

From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java

public static SSLContext initCertificates(Path certificatesDirectory, List<String> serverHostnames)
        throws Exception {
    List<String> toolkitCommandLine = new ArrayList<>(Arrays.asList("-O", "-o",
            certificatesDirectory.toFile().getAbsolutePath(), "-C", "CN=user1", "-C", "CN=user2", "-C",
            "CN=user3", "-C", "CN=user4", "-S", "badKeystorePass", "-K", "badKeyPass", "-P", "badTrustPass"));
    for (String serverHostname : serverHostnames) {
        toolkitCommandLine.add("-n");
        toolkitCommandLine.add(serverHostname);
    }//from  w w w . j a  v a 2  s .co  m
    Files.createDirectories(certificatesDirectory);
    TlsToolkitStandaloneCommandLine tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(toolkitCommandLine.toArray(new String[toolkitCommandLine.size()]));
    new TlsToolkitStandalone()
            .createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(new String[] { "-O", "-o",
            certificatesDirectory.getParent().resolve("badCert").toFile().getAbsolutePath(), "-C",
            "CN=user3" });
    new TlsToolkitStandalone()
            .createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    final KeyStore trustStore = KeyStoreUtils.getTrustStore("jks");
    try (final InputStream trustStoreStream = new FileInputStream(
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath())) {
        trustStore.load(trustStoreStream, "badTrustPass".toCharArray());
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return SslContextFactory.createTrustSslContext(
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath(),
            "badTrustPass".toCharArray(), "jks", "TLS");
}

From source file:com.alliander.osgp.shared.usermanagement.AuthenticationClient.java

/**
 * Construct an AuthenticationClient instance.
 *
 * @param keystoreLocation/*from w  w w  . ja  v a  2  s. c o m*/
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the AuthenticationClient.
 *
 * @throws AuthenticationClientException
 *             In case the construction fails, an
 *             AuthenticationClientException will be thrown.
 */
public AuthenticationClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws AuthenticationClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers, true);
        if (this.webClient == null) {
            throw new AuthenticationClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());

        this.jacksonObjectMapper = new ObjectMapper();
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new AuthenticationClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new AuthenticationClientException(CONSTRUCTION_FAILED, exception);
    }
}

From source file:com.cloudbees.tftwoway.Client.java

public static TrustManager[] getTrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore store = KeyStore.getInstance("JKS");

    store.load(null);/*from  ww  w.  ja va  2s. co  m*/
    X509Certificate cacerts = loadX509Key(CACERT);
    store.setCertificateEntry("cert", cacerts);

    trustManagerFactory.init(store);

    return trustManagerFactory.getTrustManagers();
}

From source file:learn.encryption.ssl.SSLContext_Https.java

public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) {
    if (sslContext != null) {
        return sslContext;
    }/*from   w ww. ja  v  a  2  s. c  o m*/
    try {
        // ??, ??assets
        //InputStream inputStream = App.getInstance().getAssets().open("serverkey.cer");
        InputStream inputStream = new FileInputStream(new File(servercerfile));
        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
        Certificate cer = cerFactory.generateCertificate(inputStream);
        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");//eclipse?jksandroidPKCS12??
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trust", cer);

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        sslContext = SSLContext.getInstance("TLS");

        //?clientKeyStore(android??bks)
        //KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        KeyStore clientKeyStore = KeyStore.getInstance("jks");
        //clientKeyStore.load(App.getInstance().getAssets().open("clientkey.bks"), "123456".toCharArray());
        clientKeyStore.load(new FileInputStream(new File(clientkeyStore)), clientPass.toCharArray());

        // ?clientKeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, clientPass.toCharArray());

        // ?SSLContext  trustManagerFactory.getTrustManagers()
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());//new TrustManager[]{trustManagers}??
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }//  ww w.ja v  a2 s .  c  o  m

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}