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.openshift.internal.restclient.authorization.AuthorizationClient.java

private X509TrustManager getCurrentTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
    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;
            break;
        }// ww  w. j av a  2  s  .  c  o m
    }
    return x509TrustManager;
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Same as buildContext(), but wraps all X509TrustManagers in a SavableTrustManager to provide
 * UntrustedCertificateExceptions so that when a client connects to a server it does not trust,
 * the program can recover the key and ask the user if they wish to trust it.
 *
 * @param trustMaterial//from w  ww  . jav  a2  s.  co  m
 * @return
 */
public static SSLContext buildClientContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);
        ctx = SSLContext.getInstance("TLS");
        //key manager factory go!
        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

        TrustManager[] trustManagers = tmf.getTrustManagers();

        for (int i = 0; i < trustManagers.length; i++) {
            if (trustManagers[i] instanceof X509TrustManager) {
                System.out.println("Wrapped a trust manager.");
                trustManagers[i] = new SavableTrustManager((X509TrustManager) trustManagers[i]);
            }
        }

        ctx.init(keyMgr.getKeyManagers(), trustManagers, null);
    } catch (KeyStoreException | UnrecoverableKeyException | KeyManagementException
            | NoSuchAlgorithmException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ctx = null;
    }

    return ctx;
}

From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java

/**
 * @throws SystemException if jceks keystore is not available on {@link ProtectorImpl#getKeyStorePath}
 *//*from  w  w  w .  ja  v  a  2s  . c om*/
public void init() {
    InputStream stream = null;
    try {
        // Test if use file or classpath resource
        File f = new File(getKeyStorePath());
        if (f.exists()) {
            LOGGER.info("Using file keystore at {}", getKeyStorePath());
            if (!f.canRead()) {
                LOGGER.error("Provided keystore file {} is unreadable.", getKeyStorePath());
                throw new EncryptionException(
                        "Provided keystore file " + getKeyStorePath() + " is unreadable.");
            }
            stream = new FileInputStream(f);

            // Use class path keystore
        } else {
            LOGGER.warn("Using default keystore from classpath ({}).", getKeyStorePath());
            // Read from class path

            stream = ProtectorImpl.class.getClassLoader().getResourceAsStream(getKeyStorePath());
            // ugly dirty hack to have second chance to find keystore on
            // class path
            if (stream == null) {
                stream = ProtectorImpl.class.getClassLoader()
                        .getResourceAsStream("com/../../" + getKeyStorePath());
            }
        }
        // Test if we have valid stream
        if (stream == null) {
            throw new EncryptionException("Couldn't load keystore as resource '" + getKeyStorePath() + "'");
        }
        // Load keystore
        keyStore.load(stream, getKeyStorePassword().toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        Set<String> keyEntryAliasesInKeyStore = new HashSet<>();

        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance(KEY_DIGEST_TYPE);
        } catch (NoSuchAlgorithmException ex) {
            throw new EncryptionException(ex.getMessage(), ex);
        }

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            try {
                if (!keyStore.isKeyEntry(alias)) {
                    LOGGER.trace("Alias {} is not a key entry and shall be skipped", alias);
                    continue;
                }
                keyEntryAliasesInKeyStore.add(alias);
                Key key = keyStore.getKey(alias, KEY_PASSWORD);
                if (!(key instanceof SecretKey)) {
                    continue;
                }
                final SecretKey secretKey = (SecretKey) key;
                LOGGER.trace("Found secret key for alias {}", alias);
                aliasToSecretKeyHashMap.put(alias, secretKey);

                final String digest = Base64.encode(sha1.digest(key.getEncoded()));
                LOGGER.trace("Calculated digest {} for key alias {}", digest, key);
                digestToSecretKeyHashMap.put(digest, secretKey);

            } catch (UnrecoverableKeyException ex) {
                LOGGER.trace("Couldn't recover key {} from keystore, reason: {}",
                        new Object[] { alias, ex.getMessage() });
            }
        }
        LOGGER.trace("Found {} aliases in keystore identified as secret keys", aliasToSecretKeyHashMap.size());
        stream.close();

        // Initialize trust manager list

        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(keyStore);
        trustManagers = new ArrayList<>();
        for (TrustManager trustManager : tmFactory.getTrustManagers()) {
            trustManagers.add(trustManager);
        }

        //init apache crypto library
        Init.init();

    } catch (Exception ex) {
        LOGGER.error("Unable to work with keystore {}, reason {}.",
                new Object[] { getKeyStorePath(), ex.getMessage() }, ex);
        throw new SystemException(ex.getMessage(), ex);
    }

    randomNumberGenerator = new SecureRandom();
}

From source file:com.salesmanager.core.service.common.impl.EasySSLProtocolSocketFactory.java

public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {

    super();/*from w w  w.  ja v a  2s. c  o m*/

    TrustManagerFactory factory = TrustManagerFactory.getInstance("SunX509");
    factory.init(keystore);

    TrustManager[] trustmanagers = factory.getTrustManagers();

    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
    }

    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}

From source file:net.myrrix.client.ClientRecommender.java

private SSLSocketFactory buildSSLSocketFactory() throws IOException {

    final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override//  w  w  w . j  a  v a 2 s  .  co m
        public boolean verify(String hostname, SSLSession sslSession) {
            return ignoreHTTPSHost || "localhost".equals(hostname) || "127.0.0.1".equals(hostname)
                    || defaultVerifier.verify(hostname, sslSession);
        }
    });

    try {

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File trustStoreFile = config.getKeystoreFile().getAbsoluteFile();
        String password = config.getKeystorePassword();
        Preconditions.checkNotNull(password);

        InputStream in = new FileInputStream(trustStoreFile);
        try {
            keyStore.load(in, password.toCharArray());
        } finally {
            in.close();
        }

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

        SSLContext ctx;
        try {
            ctx = SSLContext.getInstance("TLSv1.1"); // Java 7 only
        } catch (NoSuchAlgorithmException ignored) {
            log.info("TLSv1.1 unavailable, falling back to TLSv1");
            ctx = SSLContext.getInstance("TLSv1"); // Java 6       
            // This also seems to be necessary:
            if (System.getProperty("https.protocols") == null) {
                System.setProperty("https.protocols", "TLSv1");
            }
        }
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx.getSocketFactory();

    } catch (NoSuchAlgorithmException nsae) {
        // can't happen?
        throw new IllegalStateException(nsae);
    } catch (KeyStoreException kse) {
        throw new IOException(kse);
    } catch (KeyManagementException kme) {
        throw new IOException(kme);
    } catch (CertificateException ce) {
        throw new IOException(ce);
    }
}

From source file:org.wildfly.elytron.web.undertow.server.ClientCertAuthenticationTest.java

/**
 * Get the trust manager that trusts all certificates signed by the certificate authority.
 *
 * @return the trust manager that trusts all certificates signed by the certificate authority.
 * @throws KeyStoreException//from www  .  j  av a2s .  c  o  m
 */
private X509TrustManager getCATrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(loadKeyStore("/tls/ca.truststore"));

    for (TrustManager current : trustManagerFactory.getTrustManagers()) {
        if (current instanceof X509TrustManager) {
            return (X509TrustManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509TrustManager.");
}

From source file:org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.OAuthRequestInterceptor.java

private static SSLSocketFactory initSSLConnection(KeyStore keyStore, String keyStorePassword,
        KeyStore trustStore)//from   w w w. ja v  a2  s  . c  o  m
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication
    SSLContext sslContext = SSLContext.getInstance("SSLv3");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
    return sslContext.getSocketFactory();
}

From source file:com.android.beyondemail.SSLSocketFactory.java

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

From source file:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public void sendRequest(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, KeyManagementException {
    // Get the key store that includes self-signed cert as a "trusted"
    // entry.//from  w w w .ja va  2s .co m
    InputStream keyStoreStream = GenerateORU_R01Alert.class.getResourceAsStream("/truststore-prod.jks");

    // Load the keyStore

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, keystorePassword.toCharArray());
    log.info("KeyStoreStream = " + IOUtils.toString(keyStoreStream));
    keyStoreStream.close();

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

    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);

    // set SSL Factory to be used for all HTTPS connections
    sslFactory = ctx.getSocketFactory();

    callQueryFacility(msg, e);

}

From source file:sabina.integration.TestScenario.java

/**
 * Convenience method to use own truststore on SSL Sockets. Will default to
 * the self signed keystore provided in resources, but will respect
 * <p>/* w w w.ja  v a2  s. c o m*/
 * -Djavax.net.ssl.keyStore=serverKeys
 * -Djavax.net.ssl.keyStorePassword=password
 * -Djavax.net.ssl.trustStore=serverTrust
 * -Djavax.net.ssl.trustStorePassword=password SSLApplication
 * <p>
 * So these can be used to specify other key/trust stores if required.
 *
 * @return an SSL Socket Factory using either provided keystore OR the
 * keystore specified in JVM params
 */
private SSLSocketFactory getSslFactory() {
    KeyStore keyStore;

    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream fis = new FileInputStream(getTrustStoreLocation());
        keyStore.load(fis, getTrustStorePassword().toCharArray());
        fis.close();

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}