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.kontalk.client.KontalkConnection.java

@SuppressLint("AllowAllHostnameVerifier")
private static void setupSSL(XMPPTCPConnectionConfiguration.Builder builder, boolean direct,
        PrivateKey privateKey, X509Certificate bridgeCert, boolean acceptAnyCertificate, KeyStore trustStore) {
    try {/*from   w  w w.j  a  va2 s.  com*/
        SSLContext ctx = SSLContext.getInstance("TLS");

        KeyManager[] km = null;
        if (privateKey != null && bridgeCert != null) {
            // in-memory keystore
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert });

            // key managers
            KeyManagerFactory kmFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmFactory.init(keystore, null);

            km = kmFactory.getKeyManagers();

            // disable PLAIN mechanism if not upgrading from legacy
            if (!LegacyAuthentication.isUpgrading()) {
                // blacklist PLAIN mechanism
                SASLAuthentication.blacklistSASLMechanism("PLAIN");
            }
        }

        // trust managers
        TrustManager[] tm;

        if (acceptAnyCertificate) {
            tm = new TrustManager[] { new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
            } };
            builder.setHostnameVerifier(new AllowAllHostnameVerifier());
        }

        else {
            // builtin keystore
            TrustManagerFactory tmFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmFactory.init(trustStore);

            tm = tmFactory.getTrustManagers();
        }

        ctx.init(km, tm, null);
        builder.setCustomSSLContext(ctx);
        if (direct)
            builder.setSocketFactory(ctx.getSocketFactory());

        // SASL EXTERNAL is already enabled in Smack
    } catch (Exception e) {
        Log.w(TAG, "unable to setup SSL connection", e);
    }
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception {
    InputStream caCertInputStream = null;
    try {//from w  ww.  jav a2  s. c om
        caCertInputStream = context.getResources().openRawResource(R.raw.ca);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

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

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
    }
}

From source file:org.elasticsearch.xpack.ssl.SSLClientAuthTests.java

private SSLContext getSSLContext() {
    try (InputStream in = Files.newInputStream(
            getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.jks"))) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(in, "testclient".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);//from  w  w w  .  j  a  v a  2 s  .  c o  m
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "testclient".toCharArray());
        SSLContext context = SSLContext.getInstance("TLSv1.2");
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        return context;
    } catch (Exception e) {
        throw new ElasticsearchException("failed to initialize a TrustManagerFactory", e);
    }
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) {
    this.sslParser = sslParser;
    try {/*  w  w w .j  av a 2 s . co  m*/
        String algorihm = KeyManagerFactory.getDefaultAlgorithm();
        if (sslParser.getAlgorithm() != null)
            algorihm = sslParser.getAlgorithm();

        KeyManagerFactory kmf = null;
        String keyStoreType = "JKS";
        if (sslParser.getKeyStore() != null) {
            if (sslParser.getKeyStore().getKeyAlias() != null)
                throw new InvalidParameterException("keyAlias is not yet supported.");
            char[] keyPass = "changeit".toCharArray();
            if (sslParser.getKeyStore().getKeyPassword() != null)
                keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray();

            if (sslParser.getKeyStore().getType() != null)
                keyStoreType = sslParser.getKeyStore().getType();
            KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation);
            kmf = KeyManagerFactory.getInstance(algorihm);
            kmf.init(ks, keyPass);

            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    // first key is used by the KeyManagerFactory
                    Certificate c = ks.getCertificate(alias);
                    if (c instanceof X509Certificate) {
                        X509Certificate x = (X509Certificate) c;

                        dnsNames = new ArrayList<String>();

                        Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames();
                        if (subjectAlternativeNames != null)
                            for (List<?> l : subjectAlternativeNames) {
                                if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2))
                                    dnsNames.add(l.get(1).toString());
                            }
                    }
                    break;
                }
            }

        }
        TrustManagerFactory tmf = null;
        if (sslParser.getTrustStore() != null) {
            String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            if (sslParser.getTrustStore().getAlgorithm() != null)
                trustAlgorithm = sslParser.getTrustStore().getAlgorithm();
            KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver,
                    baseLocation);
            tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            tmf.init(ks);
        }

        TrustManager[] tms = tmf != null ? tmf.getTrustManagers()
                : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */;
        if (sslParser.isIgnoreTimestampCheckFailure())
            tms = new TrustManager[] { new TrustManagerWrapper(tms, true) };

        if (sslParser.getProtocol() != null)
            sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol());
        else
            sslc = javax.net.ssl.SSLContext.getInstance("TLS");

        sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null);

        if (sslParser.getCiphers() != null) {
            ciphers = sslParser.getCiphers().split(",");
            Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites());
            for (String cipher : ciphers) {
                if (!supportedCiphers.contains(cipher))
                    throw new InvalidParameterException("Unknown cipher " + cipher);
                if (cipher.contains("_RC4_"))
                    log.warn("Cipher " + cipher + " uses RC4, which is deprecated.");
            }
        } else {
            // use all default ciphers except those using RC4
            String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites();
            ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length);
            for (String cipher : supportedCiphers)
                if (!cipher.contains("_RC4_"))
                    ciphers.add(cipher);
            sortCiphers(ciphers);
            this.ciphers = ciphers.toArray(new String[ciphers.size()]);
        }
        if (setUseCipherSuitesOrderMethod == null)
            log.warn(
                    "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients.");

        if (sslParser.getProtocols() != null) {
            protocols = sslParser.getProtocols().split(",");
        } else {
            protocols = null;
        }

        if (sslParser.getClientAuth() == null) {
            needClientAuth = false;
            wantClientAuth = false;
        } else if (sslParser.getClientAuth().equals("need")) {
            needClientAuth = true;
            wantClientAuth = true;
        } else if (sslParser.getClientAuth().equals("want")) {
            needClientAuth = false;
            wantClientAuth = true;
        } else {
            throw new RuntimeException("Invalid value '" + sslParser.getClientAuth()
                    + "' in clientAuth: expected 'want', 'need' or not set.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from w  w w  .jav a2  s. com*/
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    return trustmanagers;
}

From source file:com.netflix.discovery.shared.EurekaJerseyClient.java

private static TrustManager[] createTrustManagers(KeyStore trustStore) {
    TrustManagerFactory factory = null;
    try {//from  w  w  w .  j av  a  2  s .  c o m
        factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init(trustStore);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    final TrustManager[] managers = factory.getTrustManagers();

    return managers;

}

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

/**
 * @description javaSSLContext//ww w .  ja  v a  2s. c  o  m
 * @description https?, SSLContext (NoHttp?SecureRandombug)
 * @description client.ks?server
 * @description ??
 * @description ????getSSLContext2()
 */
//@SuppressLint("TrulyRandom")
public static SSLContext getSSLContext() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        // ??, ??assets
        InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks"));
        //App.getInstance().getAssets().open("srca.cer");

        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");

        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(inputStream, "123456".toCharArray());
        //Certificate cer = cerFactory.generateCertificate(inputStream);
        Certificate cer = keyStore.getCertificate("clientKey");
        keyStore.setCertificateEntry("trust", cer);

        // KeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "123456".toCharArray());

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

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

    return sslContext;
}

From source file:com.codedx.burp.security.SSLConnectionSocketFactoryFactory.java

private static X509TrustManager getDefaultTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
    TrustManagerFactory defaultFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    defaultFactory.init((KeyStore) null);

    TrustManager[] managers = defaultFactory.getTrustManagers();
    for (TrustManager mgr : managers) {
        if (mgr instanceof X509TrustManager) {
            return (X509TrustManager) mgr;
        }/*from  w  w w.  j  a  v a2s .co  m*/
    }

    return null;
}

From source file:com.vmware.photon.controller.common.auth.AuthOIDCClient.java

private IdmClient createIdmClient(String domainControllerFQDN, int domainControllerPort, String user,
        String password) throws AuthException {
    try {//from   w  w w  .ja v a 2s .  com
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(certificateStore.getKeyStore());
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort,
                new DefaultHostnameVerifier(), sslContext);

        com.vmware.identity.openidconnect.client.AccessToken accessToken = getTokenHandler()
                .getAdminServerAccessToken(user, password).getAccessToken();

        com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
                accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
        idmClient.setToken(restAccessToken);
        return idmClient;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new AuthException("Failed to createIdmClient", e);
    }
}

From source file:org.wso2.carbon.inbound.ibmmq.poll.IbmMqConsumer.java

public void sslConnection() {
    String keyStoreLocation = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_LOCATION);
    String keyStoreType = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_TYPE);
    String keyStorePassword = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_PASSWORD);
    String trustStoreLocation = properties.getProperty(ibmMqConstant.SSL_TRUSTSTORE_LOCATION);
    String trustStoreType = properties.getProperty(ibmMqConstant.SSL_TRUSTSTORE_TYPE);
    String sslVersion = properties.getProperty(ibmMqConstant.SSL_VERSION);
    String sslFipsRequired = properties.getProperty(ibmMqConstant.SSL_FIPS);
    String sslCipherSuite = properties.getProperty(ibmMqConstant.SSL_CIPHERSUITE);
    boolean sslFips = Boolean.parseBoolean(sslFipsRequired);
    try {/*  w w  w . ja  v  a 2  s  .  co  m*/
        char[] keyPassphrase = keyStorePassword.toCharArray();
        KeyStore ks = KeyStore.getInstance(keyStoreType);
        ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);
        KeyStore trustStore = KeyStore.getInstance(trustStoreType);
        trustStore.load(new FileInputStream(trustStoreLocation), null);

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

        trustManagerFactory.init(trustStore);
        keyManagerFactory.init(ks, keyPassphrase);
        SSLContext sslContext = SSLContext.getInstance(sslVersion);
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        MQEnvironment.sslSocketFactory = sslContext.getSocketFactory();
        MQEnvironment.sslFipsRequired = sslFips;
        MQEnvironment.sslCipherSuite = sslCipherSuite;
    } catch (Exception ex) {
        handleException(ex.getMessage());
    }
}