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: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   ww  w.  j  a  va  2s .com*/
 * @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}
 *///w ww .j  av  a2 s  . 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:net.myrrix.client.ClientRecommender.java

private SSLSocketFactory buildSSLSocketFactory() throws IOException {

    final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override/*from  w  ww. j  a v a 2  s . com*/
        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 w w w. ja v  a  2  s. c  om
 */
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: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");
    }//from ww  w .j a va2  s .com
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    return tmfactory.getTrustManagers();
}

From source file:com.sonatype.nexus.ssl.plugin.internal.TrustStoreImpl.java

private static TrustManager[] getSystemTrustManagers() throws Exception {
    TrustManagerFactory trustManagerFactory;

    String trustAlgorithm = System.getProperty("ssl.TrustManagerFactory.algorithm");
    if (trustAlgorithm == null) {
        trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    }//from   w w  w  .j a va  2 s .co  m
    String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
    if (trustStoreType == null) {
        trustStoreType = KeyStore.getDefaultType();
    }
    if ("none".equalsIgnoreCase(trustStoreType)) {
        trustManagerFactory = TrustManagerFactory.getInstance(trustAlgorithm);
    } else {
        File trustStoreFile;
        KeyStore trustStore;

        String trustStoreFileName = System.getProperty("javax.net.ssl.trustStore");
        if (trustStoreFileName != null) {
            trustStoreFile = new File(trustStoreFileName);
            trustManagerFactory = TrustManagerFactory.getInstance(trustAlgorithm);
            final String trustStoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider");
            if (trustStoreProvider != null) {
                trustStore = KeyStore.getInstance(trustStoreType, trustStoreProvider);
            } else {
                trustStore = KeyStore.getInstance(trustStoreType);
            }
        } else {
            File javaHome = new File(System.getProperty("java.home"));
            File file = new File(javaHome, "lib/security/jssecacerts");
            if (!file.exists()) {
                file = new File(javaHome, "lib/security/cacerts");
                trustStoreFile = file;
            } else {
                trustStoreFile = file;
            }

            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        }
        final String password = System.getProperty("javax.net.ssl.trustStorePassword");
        try (FileInputStream in = new FileInputStream(trustStoreFile)) {
            trustStore.load(in, password != null ? password.toCharArray() : null);
        }
        trustManagerFactory.init(trustStore);
    }
    return trustManagerFactory.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  ww w. jav a  2 s . c om
    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>/*from  ww  w.  ja va2 s  . co  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;
    }
}

From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.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  .  java  2  s  .com*/
    logger.debug("createTrustManagers - Initializing trust manager: " + keystore.aliases().nextElement());
    logger.debug("Initializing trust manager");
    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;
}

From source file:org.apache.jmeter.util.JsseSSLManager.java

private SSLContext createContext() throws GeneralSecurityException {
    SSLContext context;/*from   w w w  .  j  a  v  a 2s  .c  om*/
    if (pro != null) {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, pro); // $NON-NLS-1$
    } else {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL); // $NON-NLS-1$
    }
    KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    JmeterKeyStore keys = this.getKeyStore();
    managerFactory.init(null, defaultpw == null ? new char[] {} : defaultpw.toCharArray());
    KeyManager[] managers = managerFactory.getKeyManagers();
    KeyManager[] newManagers = new KeyManager[managers.length];

    log.debug(keys.getClass().toString());

    // Now wrap the default managers with our key manager
    for (int i = 0; i < managers.length; i++) {
        if (managers[i] instanceof X509KeyManager) {
            X509KeyManager manager = (X509KeyManager) managers[i];
            newManagers[i] = new WrappedX509KeyManager(manager, keys);
        } else {
            newManagers[i] = managers[i];
        }
    }

    // Get the default trust managers
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(this.getTrustStore());

    // Wrap the defaults in our custom trust manager
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new CustomX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    context.init(newManagers, trustmanagers, this.rand);
    if (log.isDebugEnabled()) {
        String[] dCiphers = context.getSocketFactory().getDefaultCipherSuites();
        String[] sCiphers = context.getSocketFactory().getSupportedCipherSuites();
        int len = (dCiphers.length > sCiphers.length) ? dCiphers.length : sCiphers.length;
        for (int i = 0; i < len; i++) {
            if (i < dCiphers.length) {
                log.debug("Default Cipher: " + dCiphers[i]);
            }
            if (i < sCiphers.length) {
                log.debug("Supported Cipher: " + sCiphers[i]);
            }
        }
    }
    return context;
}