Example usage for javax.net.ssl TrustManagerFactory getInstance

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

Introduction

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

Prototype

public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a TrustManagerFactory object that acts as a factory for trust managers.

Usage

From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java

private TrustManager[] createTrustManagers(final KeyStore keyStore)
        throws KeyStoreException, NoSuchAlgorithmException {
    log.debug("Initializing trust managers");

    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keyStore);/* w  w w  .  j a  v a  2 s.c o  m*/

    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; ++i) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new LtX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:com.gsf.dowload.nfe.HSProtocolSocketFactory.java

public TrustManager[] createTrustManagers()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore trustStore = KeyStore.getInstance("JKS");

    trustStore.load(new FileInputStream(TRUSTSTORE), "sistec".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    return trustManagerFactory.getTrustManagers();
}

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//from   www  . j av  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.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result/* www  . j  av  a2s .  co  m*/
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation()
            + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassphrase);

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport,
        final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keystore);//from  w ww  .j a v a 2 s  . c o  m
    final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0];
    final MyTrustManager tm = new MyTrustManager(dtm);
    context.init(null, new TrustManager[] { tm }, null);
    final SSLSocketFactory factory = context.getSocketFactory();
    final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println("Certificate for server " + sitehostname + " is already trusted");
    } catch (SSLException e) {
        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.err.println("Could not obtain server certificate chain");
            return keystore;
        }
        System.out.println("Server sent " + chain.length + " certificate(s):");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            MessageDigest.getInstance("SHA1").update(cert.getEncoded());
            MessageDigest.getInstance("MD5").update(cert.getEncoded());
            final String alias = sitehostname + "-" + (i + 1);
            keystore.setCertificateEntry(alias, cert);
            System.out.println("Added certificate to keystore using alias '" + alias + "'");
        }
    }
    return keystore;
}

From source file:com.mgmtp.jfunk.web.ssl.JFunkSSLSocketFactory.java

private TrustManager[] createTrustManagers(final KeyStore keyStore)
        throws KeyStoreException, NoSuchAlgorithmException {
    log.debug("Initializing trust managers");

    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keyStore);/*from   w w  w . ja  v a 2s  . c  o  m*/

    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; ++i) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new JFunkX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:com.netflix.spinnaker.orca.webhook.config.WebhookConfiguration.java

private X509TrustManager getTrustManager(KeyStore keyStore) {
    try {/*from ww w  . j  a v  a2  s  . co  m*/
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        return (X509TrustManager) trustManagers[0];
    } catch (KeyStoreException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jasig.cas.authentication.FileTrustStoreSslSocketFactory.java

/**
 * Gets trust manager.//from  w  ww  .j ava 2s  .c o m
 *
 * @param algorithm the algorithm
 * @param keystore the keystore
 * @return the trust manager
 * @throws Exception the exception
 */
private static X509TrustManager getTrustManager(final String algorithm, final KeyStore keystore)
        throws Exception {
    final TrustManagerFactory factory = TrustManagerFactory.getInstance(algorithm);
    factory.init(keystore);
    return (X509TrustManager) factory.getTrustManagers()[0];
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) {
    SSLSocket socket;//from  www .  j  a v a2 s  . com
    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        //          keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());

        // This works when built with Eclipse, but not when built from command line. 
        // Has to do with where the build system puts /resources/*.p12 file
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray());

        // Currently only works when read from the server's FS. Won't currently read from within eclipse project. 
        // Putting it in /opt/kme/push prevents naming conflicts. 
        keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
        keyManagerFactory.init(keyStore, "strange word to use".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
        trustManagerFactory.init(keyStore);
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        socket.startHandshake();

        //Diagnostic output
        Enumeration e = keyStore.aliases();
        LOG.info(e.toString());
        while (e.hasMoreElements()) {
            LOG.info("Alias: " + e.nextElement().toString());
        }

        String not = (socket.isConnected()) ? "" : "NOT ";
        LOG.info("SSLSocket is " + not + "Connected");

        LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName());
        LOG.info("Connected to: " + socket.getInetAddress().getHostAddress());

        String cs[] = socket.getEnabledCipherSuites();
        LOG.info("CipherSuites: " + Arrays.toString(cs));

        String ep[] = socket.getEnabledProtocols();
        LOG.info("Enabled Protocols: " + Arrays.toString(ep));

        LOG.info("Timeout: " + socket.getSoTimeout());
        LOG.info("Send Buffer Size: " + socket.getSendBufferSize());

        return socket;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:at.diamonddogs.net.SSLHelper.java

/**
 * Register a keystore with SSL (JAVA)//from w w  w. j av  a  2 s .c o m
 * 
 * @param c
 *            a {@link Context}
 * @param resourceId
 *            the resource id of the keystore
 * @param password
 *            the password of the keystore
 * @return true on success, false otherwise
 */
public boolean initSSLFactoryJava(Context c, int resourceId, String password) {
    try {
        if (c == null || resourceId == -1 || password == null) {
            LOGGER.info("No keystore specified, using alltrust");
            makeAllTrustManagerForJava();
            return true;
        } else {
            KeyStore store = getKeyStore(c, resourceId, password);
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(store);
            SSLContext sslCtx = SSLContext.getInstance("TLS");
            sslCtx.init(null, tmf.getTrustManagers(), null);
            SSL_FACTORY_JAVA = sslCtx.getSocketFactory();
            sslState.trustAll = false;
            return true;
        }
    } catch (Throwable tr) {
        LOGGER.warn("Error initializing SSLFactoryJava", tr);
        try {
            makeAllTrustManagerForJava();
            sslState.tr = tr;
            return true;
        } catch (Throwable tr1) {
            sslState.tr1 = tr1;
            sslState.sslOk = false;
            LOGGER.warn("Error trusting all certs, no ssl connection possible", tr);
        }
        return false;
    }
}