Example usage for javax.net.ssl KeyManagerFactory getDefaultAlgorithm

List of usage examples for javax.net.ssl KeyManagerFactory getDefaultAlgorithm

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getDefaultAlgorithm.

Prototype

public static final String getDefaultAlgorithm() 

Source Link

Document

Obtains the default KeyManagerFactory algorithm name.

Usage

From source file:com.googlecode.xremoting.core.commonshttpclient.ssl.AuthSSLProtocolSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from   w w w  .j  av  a  2s.co  m*/
    LOG.debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    KeyManager[] keymanagers = kmfactory.getKeyManagers();
    for (int i = 0; i < keymanagers.length; i++) {
        if (keymanagers[i] instanceof X509KeyManager) {
            keymanagers[i] = new AuthSSLX509KeyManager((X509KeyManager) keymanagers[i]);
        }
    }
    return keymanagers;
}

From source file:mitm.common.security.ca.handlers.ejbca.EJBCACertificateRequestHandler.java

private EjbcaWS getEjbcaWS() throws CAException {
    if (ejbcaWS == null) {
        try {//from   w  w  w. ja v  a2  s.  c o  m
            JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

            factory.setServiceClass(EjbcaWS.class);
            factory.setAddress(requestHandlerSettings.getWebServiceURL().toExternalForm());
            factory.setServiceName(EJBCAConst.SERVICE_NAME);
            EjbcaWS localEjbcaWS = (EjbcaWS) factory.create();

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

            char[] password = requestHandlerSettings.getKeyStorePassword() != null
                    ? requestHandlerSettings.getKeyStorePassword().toCharArray()
                    : null;

            keyManagerFactory.init(requestHandlerSettings.getKeyStore(), password);

            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            Client proxy = ClientProxy.getClient(localEjbcaWS);

            TLSClientParameters tlsClientParameters = new TLSClientParameters();

            tlsClientParameters.setDisableCNCheck(requestHandlerSettings.isDisableCNCheck());

            if (requestHandlerSettings.isSkipCertificateCheck()) {
                /*
                 * Use a TrustManager that skips all checks 
                 */
                tlsClientParameters.setTrustManagers(new TrustManager[] { new TrustAllX509TrustManager() });
            } else {
                KeyStore trustStore = requestHandlerSettings.getTrustStore();

                if (trustStore != null) {
                    /*
                     * Use the provided trust store
                     */
                    TrustManagerFactory trustManagerFactory = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

                    trustManagerFactory.init(trustStore);

                    tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers());
                }
            }

            tlsClientParameters.setKeyManagers(keyManagers);

            HTTPConduit conduit = (HTTPConduit) proxy.getConduit();

            conduit.setTlsClientParameters(tlsClientParameters);

            ejbcaWS = localEjbcaWS;
        } catch (NoSuchAlgorithmException e) {
            throw new CAException(e);
        } catch (UnrecoverableKeyException e) {
            throw new CAException(e);
        } catch (KeyStoreException e) {
            throw new CAException(e);
        }
    }

    return ejbcaWS;
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null)
        throw new IllegalArgumentException("Keystore may not be null");

    Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

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 www  . j ava  2s.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:org.apache.synapse.transport.nhttp.HttpCoreNIOSSLSender.java

private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert)
        throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    if (keyStoreElt != null) {
        String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {//  ww  w  . j a v a2  s  .co  m
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Identity Keystore from : " + location);

            keyStore.load(fis, storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Keystore : " + location, gse);
            throw new AxisFault("Error loading Keystore : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Keystore : " + location, ioe);
            throw new AxisFault("Error opening Keystore : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreElt != null) {
        if (novalidatecert) {
            log.warn("Ignoring novalidatecert parameter since a truststore has been specified");
        }

        String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText();

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Trust Keystore from : " + location);

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    } else if (novalidatecert) {
        log.warn("Server certificate validation (trust) has been disabled. " + "DO NOT USE IN PRODUCTION!");
        trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
    }

    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

    } catch (GeneralSecurityException gse) {
        log.error("Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *//*ww w.java 2  s. co  m*/
protected SSLConnectionSocketFactory getSocketFactory() throws IOException {
    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;

    try {
        /* trust managers */
        if (caCertificateFile != null) {
            KeyStore trustStore;
            int cn = 0;

            log.info("Setting x509 trust from " + caCertificateFile);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(caCertificateFile);
            Collection certs = cf.generateCertificates(in);

            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            Iterator cit = certs.iterator();
            while (cit.hasNext()) {
                X509Certificate cert = (X509Certificate) cit.next();
                log.info(" adding " + cert.getSubjectX500Principal().toString());
                System.out.println(" adding " + cert.getSubjectX500Principal().toString());
                trustStore.setCertificateEntry("CACERT" + cn, cert);
                cn += 1;
            }
            tmf.init(trustStore);
            trustManagers = tmf.getTrustManagers();
        } else { // no verification
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    return;
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    return;
                }
            } };
        }

        /* key manager */
        if (certificateFile != null && keyFile != null) {
            KeyStore keyStore;
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            FileInputStream in = new FileInputStream(certificateFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            PKCS1 pkcs = new PKCS1();
            log.info("reading key file: " + keyFile);
            PrivateKey key = pkcs.readKey(keyFile);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);
            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }

        /* socket factory */

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        return new SSLConnectionSocketFactory(ctx);

    } catch (IOException e) {
        log.error("error reading cert or key error: " + e);
    } catch (KeyStoreException e) {
        log.error("keystore error: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.error("sf error: " + e);
    } catch (KeyManagementException e) {
        log.error("sf error: " + e);
    } catch (CertificateException e) {
        log.error("sf error: " + e);
    } catch (UnrecoverableKeyException e) {
        log.error("sf error: " + e);
    }

    return null;

}

From source file:com.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClientConnectionManager createConnectionManager() {
    PoolingHttpClientConnectionManager manager;
    if ("https".equals(graphiteScheme) && !StringUtils.isEmpty(graphiteKeyStore)
            && !StringUtils.isEmpty(graphiteKeyStorePassword) && !StringUtils.isEmpty(graphiteTrustStore)) {
        try {//w  w  w  .j  a va 2s  .c  o m
            KeyStore keyStore = loadKeyStore(graphiteKeyStore, graphiteKeyStorePassword);
            KeyStore trustStore = loadKeyStore(graphiteTrustStore, null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, graphiteKeyStorePassword.toCharArray());
            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(keyManagers, trustManagers, null);

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("https", sslsf).build();

            manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (Exception e) {
            LOGGER.warn("A problem occurred when building SSLConnectionSocketFactory", e);
            throw new RuntimeException("Error while building SSLConnectionSocketFactory", e);
        }
    } else {
        manager = new PoolingHttpClientConnectionManager();
    }

    manager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    return manager;
}

From source file:org.exoplatform.services.videocall.AuthService.java

protected static KeyManager[] getKeyManagers(String keyStoreType, InputStream keyStoreFile,
        String keyStorePassword) throws Exception {
    KeyStore keyStore = null;// w  w  w. j  ava 2s. co m
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreFile, keyStorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate PKCS12 keystores");
        }
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate PKCS12 keystores");
        }
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Bad key or certificate in " + keyStoreFile, e.getMessage());
        }
    } catch (FileNotFoundException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not find or read " + keyStoreFile, e.getMessage());
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("PKCS12 password is incorrect or keystore is inconsistent: " + keyStoreFile);
        }
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePassword.toCharArray());
    return kmf.getKeyManagers();
}

From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Configure {@link SSLContext} and create EJB client properties.
 *
 * @param clientName//ww  w .  j  a  v a  2s .c o  m
 * @return
 * @throws Exception
 */
private Properties configureEjbClient(String clientName) throws Exception {
    // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(
            KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()),
            KEYSTORE_PASSWORD.toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory
            .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray()));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);

    final Properties env = new Properties();
    env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
    env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST);
    env.put("jboss.naming.client.ejb.context", "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
    env.put(Context.SECURITY_PRINCIPAL, "admin");
    env.put(Context.SECURITY_CREDENTIALS, "testing");

    // SSL related config parameters
    env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
            "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
    return env;
}

From source file:org.sandrob.android.net.http.HttpsConnection.java

/**
 * /*from   w ww .  j a  va2 s. com*/
 *
 * @param sessionDir directory to cache SSL sessions
 * @param req request that call this function
 */
public void initializeEngine(File sessionDir, Request req) {
    if (mSslSocketFactory == null) {
        String certificateFullPathName = null;
        String keyStoreType = "PKCS12";
        String keyStoreProvider = "BC";
        String certificatePassword = null;
        try {
            SSLClientSessionCache cache = null;
            KeyManager[] keyManagers = null;
            KeyStore keyStore = null;
            if (sessionDir != null) {
                Log.d("HttpsConnection", "Caching SSL sessions in " + sessionDir + ".");
                cache = FileClientSessionCache.usingDirectory(sessionDir);
            }

            // Inform the user if we need ssl client settings
            if (true) {

                synchronized (mSuspendLock) {
                    mSuspended = true;
                }
                // don't hold the lock while calling out to the event handler
                boolean canHandle = req.getEventHandler().handleSslClientSetingsRequest();
                if (!canHandle) {
                    throw new IOException("failed to handle ssl client settings ");
                }
                synchronized (mSuspendLock) {
                    if (mSuspended) {
                        try {
                            // Put a limit on how long we are waiting; if the timeout
                            // expires (which should never happen unless you choose
                            // to ignore the SSL error dialog for a very long time),
                            // we wake up the thread and abort the request. This is
                            // to prevent us from stalling the network if things go
                            // very bad.
                            mSuspendLock.wait(10 * 60 * 1000);
                            if (mSuspended) {
                                // mSuspended is true if we have not had a chance to
                                // restart the connection yet (ie, the wait timeout
                                // has expired)
                                mSuspended = false;
                                mAborted = true;
                                if (HttpLog.LOGV) {
                                    HttpLog.v("HttpsConnection.openConnection():"
                                            + " SSL timeout expired and request was cancelled!!!");
                                }
                            }
                        } catch (InterruptedException e) {
                            // ignore
                        }
                    }
                    if (mAborted) {
                        // The user decided not to use this unverified connection
                        // so close it immediately.
                        throw new SSLConnectionClosedByUserException("connection closed by the user");
                    }
                    if (mSslClientCertificate != null) {
                        // we have some data about client certificate
                        certificateFullPathName = mSslClientCertificate.getCertificateFileName();
                        certificatePassword = mSslClientCertificate.getCertificateFilePassword();
                    }
                }
            }

            SSLContextImpl sslContext = new SSLContextImpl();
            //SSLContext sslContext = SSLContext.getInstance("TLS");
            if (certificateFullPathName != null && certificatePassword != null) {
                File certFile = new File(certificateFullPathName);
                if (certFile.exists()) {
                    keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider);
                    keyStore.load(new FileInputStream(new File(certificateFullPathName)),
                            certificatePassword.toCharArray());

                    String kmfa = KeyManagerFactory.getDefaultAlgorithm();
                    KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfa);
                    kmf.init(keyStore, certificatePassword.toCharArray());
                    keyManagers = kmf.getKeyManagers();
                }
            }

            // here, trust managers is a single trust-all manager
            TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };

            sslContext.engineInit(keyManagers, trustManagers, null, cache, null);
            //sslContext.init(keyManagers, trustManagers, null);
            synchronized (HttpsConnection.class) {
                mSslSocketFactory = sslContext.engineGetSocketFactory();
                //mSslSocketFactory = sslContext.getSocketFactory();
            }
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}