List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java
private static TrustManager[] createTrustManagers(final KeyStore keystore) throws KeyStoreException, NoSuchAlgorithmException { if (keystore == null) throw new IllegalArgumentException("Keystore may not be null"); Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Initializing trust manager"); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(keystore);/*from w w w . j ava 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 AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]); } } return trustmanagers; }
From source file:org.apache.ambari.server.controller.internal.URLStreamProvider.java
protected HttpsURLConnection getSSLConnection(String spec) throws IOException { if (sslSocketFactory == null) { synchronized (this) { if (sslSocketFactory == null) { try { FileInputStream in = new FileInputStream(new File(path)); KeyStore store = KeyStore.getInstance(type == null ? KeyStore.getDefaultType() : type); store.load(in, password.toCharArray()); in.close();/*from w w w. j ava 2 s . com*/ TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(store); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); } catch (Exception e) { throw new IOException("Can't get connection.", e); } } } } HttpsURLConnection connection = (HttpsURLConnection) (new URL(spec).openConnection()); connection.setSSLSocketFactory(sslSocketFactory); return connection; }
From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java
/** * {@inheritDoc}/*www .j a v a2s . co m*/ */ @Override public TrustManager[] createTrustManagers() { KeyInfoManager keyInfoManager = null; try { keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation()); KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager); logger.debug("Initializing trust managers"); TrustManagerFactory tmfactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(ks); return tmfactory.getTrustManagers(); } catch (Throwable e) { throw new AlfrescoRuntimeException("Unable to create key manager", e); } finally { if (keyInfoManager != null) { keyInfoManager.clear(); } } }
From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java
/** * Loads the trusted certificate authorities according to the specified properties. * * @param properties properties//ww w . ja va 2 s . c o m * @return map of certificate authorities */ private Map<String, X509Certificate> getTrustedCAs(final NiFiProperties properties) { final Map<String, X509Certificate> certificateAuthorities = new HashMap<>(); // get the path to the truststore final String truststorePath = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE); if (truststorePath == null) { throw new IllegalArgumentException("The truststore path is required."); } // get the truststore password final char[] truststorePassword; final String rawTruststorePassword = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD); if (rawTruststorePassword == null) { truststorePassword = new char[0]; } else { truststorePassword = rawTruststorePassword.toCharArray(); } // load the configured truststore try (final FileInputStream fis = new FileInputStream(truststorePath)) { final KeyStore truststore = KeyStoreUtils.getTrustStore(KeyStore.getDefaultType()); truststore.load(fis, truststorePassword); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(truststore); // consider any certificates in the truststore as a trusted ca for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { for (X509Certificate ca : ((X509TrustManager) trustManager).getAcceptedIssuers()) { certificateAuthorities.put(ca.getSubjectX500Principal().getName(), ca); } } } } catch (final Exception e) { throw new IllegalStateException("Unable to load the configured truststore: " + e); } return certificateAuthorities; }
From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java
private void doConnect(final StudioProgressMonitor monitor) throws Exception { ldapConnection = null;//from w w w .j a va 2s . co m isConnected = true; ldapConnectionConfig = new LdapConnectionConfig(); ldapConnectionConfig.setLdapHost(connection.getHost()); ldapConnectionConfig.setLdapPort(connection.getPort()); long timeout = connection.getTimeout(); if (timeout < 0) { timeout = 30000L; } ldapConnectionConfig.setTimeout(timeout); binaryAttributeDetector = new DefaultConfigurableBinaryAttributeDetector(); ldapConnectionConfig.setBinaryAttributeDetector(binaryAttributeDetector); if ((connection.getEncryptionMethod() == EncryptionMethod.LDAPS) || (connection.getEncryptionMethod() == EncryptionMethod.START_TLS)) { ldapConnectionConfig.setUseSsl(connection.getEncryptionMethod() == EncryptionMethod.LDAPS); ldapConnectionConfig.setUseTls(connection.getEncryptionMethod() == EncryptionMethod.START_TLS); try { // get default trust managers (using JVM "cacerts" key store) TrustManagerFactory factory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init((KeyStore) null); TrustManager[] defaultTrustManagers = factory.getTrustManagers(); // create wrappers around the trust managers StudioTrustManager[] trustManagers = new StudioTrustManager[defaultTrustManagers.length]; for (int i = 0; i < defaultTrustManagers.length; i++) { trustManagers[i] = new StudioTrustManager((X509TrustManager) defaultTrustManagers[i]); trustManagers[i].setHost(connection.getHost()); } ldapConnectionConfig.setTrustManagers(trustManagers); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } InnerRunnable runnable = new InnerRunnable() { public void run() { try { // Set lower timeout for connecting long oldTimeout = ldapConnectionConfig.getTimeout(); ldapConnectionConfig.setTimeout(Math.min(oldTimeout, 5000L)); // Connecting ldapConnection = new LdapNetworkConnection(ldapConnectionConfig); boolean connected = ldapConnection.connect(); if (!connected) { throw new Exception(Messages.DirectoryApiConnectionWrapper_UnableToConnect); } // Set old timeout again ldapConnectionConfig.setTimeout(oldTimeout); } catch (Exception e) { exception = e; try { if (ldapConnection != null) { ldapConnection.close(); } } catch (Exception exception) { // Nothing to do } finally { ldapConnection = null; binaryAttributeDetector = null; } } } }; runAndMonitor(runnable, monitor); if (runnable.getException() != null) { throw runnable.getException(); } }
From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java
/** * Get certificates in the chain of the host server and import them. * <p>//from www. j av a 2 s .c o m * Tries to get the certificates in the certificates chain of the host * server and import them to: * <ol> * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li> * <li>The JVM cacerts keystore in * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a * problem if JVM <code>cacerts</code> file is not writable by the user due * to file permissions. In this case we throw an exception informing about * the error.</li> * </ol> * </p> * <p> * With that operation we can try again to get the WSDL.<br/> * Also it exports the chain certificates to <code>.cer</code> files in * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for * its installation in other environments or just in case we reach the * problem with the JVM <code>cacerts</code> file permissions. * </p> * * @see GvNix509TrustManager#saveCertFile(String, X509Certificate, * FileManager, PathResolver) * @see <a href= * "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html" * >Java SE keytool</a>. */ protected Document installCertificates(String loc, String pass) throws NoSuchAlgorithmException, KeyStoreException, Exception, KeyManagementException, MalformedURLException, IOException, UnknownHostException, SocketException, SAXException { // Create a SSL context SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Passphrase of the keystore: "changeit" by default char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray() : "changeit".toCharArray()); // Get the project keystore and copy it from JVM if not exists File keystore = getProjectKeystore(); tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray)); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); // Open URL location (default 443 port if not defined) URL url = new URL(loc); String host = url.getHost(); int port = url.getPort() == -1 ? 443 : url.getPort(); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); Document doc = null; try { socket.startHandshake(); URLConnection connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(factory); } doc = XmlUtils.getDocumentBuilder().parse(connection.getInputStream()); socket.close(); } catch (SSLException ssle) { // Get needed certificates for this host getCerts(tm, host, keystore, passArray); doc = getWsdl(loc, pass); } catch (IOException ioe) { invalidHostCert(passArray, keystore, tm, host); } Validate.notNull(doc, "No valid document format"); return doc; }
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 {/* www. ja v a 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:com.vmware.identity.openidconnect.client.TestUtils.java
static IdmClient createIdmClient(AccessToken accessToken, String domainControllerFQDN, int domainControllerPort, KeyStore keyStore) throws Exception { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore);/*from www . ja v a 2 s .c om*/ SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort, new DefaultHostnameVerifier(), sslContext); com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken( accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT); idmClient.setToken(restAccessToken); return idmClient; }
From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java
/** * Configure {@link SSLContext} and create EJB client properties. * * @param clientName/*from www . j a v a 2 s .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:mitm.common.security.ca.handlers.ejbca.EJBCACertificateRequestHandler.java
private EjbcaWS getEjbcaWS() throws CAException { if (ejbcaWS == null) { try {// w ww. j ava 2s . c om 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; }