Example usage for javax.net.ssl TrustManagerFactory init

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

Introduction

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

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Retrieves the certificate from the specified URL and confirms that the certificate is valid.
 *
 * @param signingCertificateChainUrl/*  ww  w .  j a  v a  2s  .  c  o m*/
 *            the URL to retrieve the certificate chain from
 * @return the certificate at the specified URL, if the certificate is valid
 * @throws CertificateException
 *             if the certificate cannot be retrieve or is invalid
 */
public static X509Certificate retrieveAndVerifyCertificateChain(final String signingCertificateChainUrl)
        throws CertificateException {
    try (InputStream in = getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openStream()) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance(Sdk.SIGNATURE_CERTIFICATE_TYPE);
        @SuppressWarnings("unchecked")
        Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory
                .generateCertificates(in);
        /*
         * check the before/after dates on the certificate date to confirm that it is valid on
         * the current date
         */
        X509Certificate signingCertificate = certificateChain.iterator().next();
        signingCertificate.checkValidity();

        // check the certificate chain
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
            }
        }

        if (x509TrustManager == null) {
            throw new IllegalStateException(
                    "No X509 TrustManager available. Unable to check certificate chain");
        } else {
            x509TrustManager.checkServerTrusted(
                    certificateChain.toArray(new X509Certificate[certificateChain.size()]),
                    Sdk.SIGNATURE_KEY_TYPE);
        }

        /*
         * verify Echo API's hostname is specified as one of subject alternative names on the
         * signing certificate
         */
        if (!subjectAlernativeNameListContainsEchoSdkDomainName(
                signingCertificate.getSubjectAlternativeNames())) {
            throw new CertificateException("The provided certificate is not valid for the Echo SDK");
        }

        return signingCertificate;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) {
        throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl,
                ex);
    }
}

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  av 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.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  ww.j  av  a  2 s  . co  m*/
        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.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   w  ww  .j  av a2  s.c o  m*/
    X509Certificate cacerts = loadX509Key(CACERT);
    store.setCertificateEntry("cert", cacerts);

    trustManagerFactory.init(store);

    return trustManagerFactory.getTrustManagers();
}

From source file:org.kontalk.client.ClientHTTPConnection.java

public static SSLSocketFactory setupSSLSocketFactory(Context context, PrivateKey privateKey,
        X509Certificate certificate, boolean acceptAnyCertificate)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException, NoSuchProviderException {

    // in-memory keystore
    KeyManager[] km = null;/*from www  .j  av  a  2  s . c om*/
    if (privateKey != null && certificate != null) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(null, null);
        keystore.setKeyEntry("private", privateKey, null, new Certificate[] { certificate });

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

    // trust managers
    TrustManager[] tm;

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

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

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        } };
    } else {
        // load merged truststore (system + internal)
        KeyStore trustStore = InternalTrustStore.getTrustStore(context);

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

        tm = tmFactory.getTrustManagers();
    }

    SSLContext ctx = SSLContext.getInstance("TLSv1");
    ctx.init(km, tm, null);
    return new TlsOnlySocketFactory(ctx.getSocketFactory(), true);
}

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

/**
 * @description javaSSLContext// w  w  w .  j  av a2s  . 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:learn.encryption.ssl.SSLContext_Https.java

public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) {
    if (sslContext != null) {
        return sslContext;
    }//  w  ww.j  a 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.springframework.vault.config.ClientHttpRequestFactoryFactory.java

private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword)
        throws GeneralSecurityException, IOException {

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

    loadKeyStore(trustFile, storePassword, trustStore);

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

    return trustManagerFactory;
}

From source file:android.apn.androidpn.server.xmpp.ssl.SSLTrustManagerFactory.java

public static TrustManager[] getTrustManagers(String storeType, String truststore, String trustpass)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    TrustManager[] trustManagers;
    if (truststore == null) {
        trustManagers = null;/*from  www  . java 2s  . c  om*/
    } else {
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        if (trustpass == null) {
            trustpass = "";
        }
        KeyStore keyStore = KeyStore.getInstance(storeType);
        keyStore.load(new FileInputStream(truststore), trustpass.toCharArray());
        trustFactory.init(keyStore);
        trustManagers = trustFactory.getTrustManagers();
    }
    return trustManagers;
}

From source file:org.miloss.fgsms.bueller.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from   www.  ja  va  2  s  .  c o m*/
    LOG.debug("Initializing trust manager");
    String alg = KeyManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory fac = TrustManagerFactory.getInstance(alg);
    fac.init(keystore);
    return fac.getTrustManagers();
    /*
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
    TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
    if (trustmanagers[i] instanceof X509TrustManager) {
        trustmanagers[i] = new AuthSSLX509TrustManager(
            (X509TrustManager)trustmanagers[i]); 
    }
    }
    return trustmanagers; */
}