List of usage examples for org.apache.http.conn.ssl SSLSocketFactory TLS
String TLS
To view the source code for org.apache.http.conn.ssl SSLSocketFactory TLS.
Click Source Link
From source file:de.kp.ames.http.HttpClient.java
/** * SSLSocketFactory can be used to validate the identity of the HTTPS server * against a list of trusted certificates (truststore) and to authenticate to * the HTTPS server using a private key (clientstore) * //from w w w .j a v a 2s . co m * @return * @throws Exception */ private SSLSocketFactory createSslSocketFactory() throws Exception { /* * Load Truststore (server certificate) */ KeyStore trustStore = KeyStoreUtil.getTrustStore(); /* * Load Clientstore (client certificate) */ KeyStore clientStore = KeyStoreUtil.getClientStore(); /* * Pass client & trust store to Socket Factory * * The factory is responsible for the verification * of the server certificate. * * /* * This tells the SSLSocketFactory to accept the certificate even if the hostname doesn't match the information from the certificate. Especially useful when testing using self-signed certificates or changing ip-addresses. */ SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, clientStore, HttpConstants.CLIENTSTORE_KEYPASS, trustStore, null, (X509HostnameVerifier) SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return socketFactory; }
From source file:org.apache.brooklyn.launcher.BrooklynWebServerTest.java
private void verifyHttpsFromConfig(BrooklynProperties brooklynProperties) throws Exception { webServer = new BrooklynWebServer(MutableMap.of(), newManagementContext(brooklynProperties)); webServer.start();/*from www .ja v a2s . co m*/ try { KeyStore keyStore = load("client.ks", "password"); KeyStore trustStore = load("client.ts", "password"); SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password", trustStore, (SecureRandom) null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder() .port(webServer.getActualPort()).https(true).socketFactory(socketFactory).build(), new HttpGet(webServer.getRootUrl())); assertEquals(response.getResponseCode(), 200); } finally { webServer.stop(); } }
From source file:org.keycloak.adapters.cloned.HttpClientBuilder.java
public HttpClient build() { X509HostnameVerifier verifier = null; if (this.verifier != null) verifier = new VerifierWrapper(this.verifier); else {//from ww w . j a v a 2 s . c om switch (policy) { case ANY: verifier = new AllowAllHostnameVerifier(); break; case WILDCARD: verifier = new BrowserCompatHostnameVerifier(); break; case STRICT: verifier = new StrictHostnameVerifier(); break; } } try { SSLSocketFactory sslsf = null; SSLContext theContext = sslContext; if (disableTrustManager) { theContext = SSLContext.getInstance("SSL"); theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom()); verifier = new AllowAllHostnameVerifier(); sslsf = new SniSSLSocketFactory(theContext, verifier); } else if (theContext != null) { sslsf = new SniSSLSocketFactory(theContext, verifier); } else if (clientKeyStore != null || truststore != null) { sslsf = new SniSSLSocketFactory(SSLSocketFactory.TLS, clientKeyStore, clientPrivateKeyPassword, truststore, null, verifier); } else { final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS); tlsContext.init(null, null, null); sslsf = new SniSSLSocketFactory(tlsContext, verifier); } SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); Scheme httpsScheme = new Scheme("https", 443, sslsf); registry.register(httpsScheme); ClientConnectionManager cm = null; if (connectionPoolSize > 0) { ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry, connectionTTL, connectionTTLUnit); tcm.setMaxTotal(connectionPoolSize); if (maxPooledPerRoute == 0) maxPooledPerRoute = connectionPoolSize; tcm.setDefaultMaxPerRoute(maxPooledPerRoute); cm = tcm; } else { cm = new SingleClientConnManager(registry); } BasicHttpParams params = new BasicHttpParams(); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (proxyHost != null) { params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); } if (socketTimeout > -1) { HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout)); } if (establishConnectionTimeout > -1) { HttpConnectionParams.setConnectionTimeout(params, (int) establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout)); } DefaultHttpClient client = new DefaultHttpClient(cm, params); if (disableCookieCache) { client.setCookieStore(new CookieStore() { @Override public void addCookie(Cookie cookie) { //To change body of implemented methods use File | Settings | File Templates. } @Override public List<Cookie> getCookies() { return Collections.emptyList(); } @Override public boolean clearExpired(Date date) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void clear() { //To change body of implemented methods use File | Settings | File Templates. } }); } return client; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.commonjava.maven.galley.transport.htcli.internal.LocationSSLSocketFactory.java
private synchronized SSLSocketFactory getSSLFactory(final HttpLocation loc) throws IOException { // logger.info( "Finding SSLSocketFactory for repo: {}", repo.getKey() ); SSLSocketFactory factory = null; // repoFactories.get( repo ); if (factory == null) { KeyStore ks = null;/*from w w w. j a v a2 s . com*/ KeyStore ts = null; final String kcPem = loc.getKeyCertPem(); final String kcPass = passwordManager.getPassword(new PasswordEntry(loc, PasswordEntry.KEY_PASSWORD)); if (kcPem != null) { if (kcPass == null || kcPass.length() < 1) { logger.error("Invalid configuration. Location: {} cannot have an empty key password!", loc.getUri()); throw new IOException("Location: " + loc.getUri() + " is misconfigured!"); } try { ks = SSLUtils.readKeyAndCert(kcPem, kcPass); // final StringBuilder sb = new StringBuilder(); // sb.append( "Keystore contains the following certificates:" ); // // for ( final Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); ) // { // final String alias = aliases.nextElement(); // final X509Certificate cert = (X509Certificate) ks.getCertificate( alias ); // // if ( cert != null ) // { // sb.append( "\n" ) // .append( cert.getSubjectDN() ); // } // } // sb.append( "\n" ); // logger.info( sb.toString() ); } catch (final CertificateException e) { logger.error(String.format( "Invalid configuration. Location: %s has an invalid client certificate! Error: %s", loc.getUri(), e.getMessage()), e); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } catch (final KeyStoreException e) { logger.error(String.format( "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s", loc.getUri(), e.getMessage()), e); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } catch (final NoSuchAlgorithmException e) { logger.error(String.format( "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s", loc.getUri(), e.getMessage()), e); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } catch (final InvalidKeySpecException e) { logger.error( String.format("Invalid configuration. Invalid client key for repository: %s. Error: %s", loc.getUri(), e.getMessage()), e); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } } final String sPem = loc.getServerCertPem(); // logger.info( "Server certificate PEM:\n{}", sPem ); if (sPem != null) { try { ts = SSLUtils.readCerts(sPem, loc.getHost()); // final StringBuilder sb = new StringBuilder(); // sb.append( "Trust store contains the following certificates:" ); // // for ( final Enumeration<String> aliases = ts.aliases(); aliases.hasMoreElements(); ) // { // final String alias = aliases.nextElement(); // final X509Certificate cert = (X509Certificate) ts.getCertificate( alias ); // if ( cert != null ) // { // sb.append( "\n" ) // .append( cert.getSubjectDN() ); // } // } // sb.append( "\n" ); // logger.info( sb.toString() ); } catch (final CertificateException e) { logger.error(String.format( "Invalid configuration. Location: %s has an invalid server certificate! Error: %s", loc.getUri(), e.getMessage()), e); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } catch (final KeyStoreException e) { logger.error(String.format( "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s", loc.getUri(), e.getMessage()), e); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } catch (final NoSuchAlgorithmException e) { logger.error(String.format( "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s", loc.getUri(), e.getMessage()), e); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } } if (ks != null || ts != null) { try { factory = new SSLSocketFactory(SSLSocketFactory.TLS, ks, kcPass, ts, null, null, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // repoFactories.put( repo, factory ); } catch (final KeyManagementException e) { logger.error( "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}", e, loc.getUri(), e.getMessage()); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } catch (final UnrecoverableKeyException e) { logger.error( "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}", e, loc.getUri(), e.getMessage()); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } catch (final NoSuchAlgorithmException e) { logger.error( "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}", e, loc.getUri(), e.getMessage()); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } catch (final KeyStoreException e) { logger.error( "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}", e, loc.getUri(), e.getMessage()); throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri()); } } } return factory; }
From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java
/** * Create the HttpContext and disable host verification * * @return//from www .jav a 2s .c o m * @throws AppFactoryException */ public HttpContext getHttpContext() throws AppFactoryException { HttpContext httpContext = new BasicHttpContext(); if (this.allowAllHostNameVerifier) { SSLContext sslContext; try { sslContext = SSLContext.getInstance(SSLSocketFactory.TLS); sslContext.init(null, null, null); } catch (KeyManagementException e) { String msg = "Error while initializing ssl context for http client"; log.error(msg, e); throw new AppFactoryException(msg, e); } catch (NoSuchAlgorithmException e) { String msg = "Error while initializing ssl context for http client"; log.error(msg, e); throw new AppFactoryException(msg, e); } SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", 443, sf); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } return httpContext; }
From source file:org.ovirt.engine.sdk.web.ConnectionsPoolBuilder.java
/** * Creates SchemeRegistry//w w w .j av a 2 s . co m * * @param url * @param port * * @return {@link SchemeRegistry} */ private SchemeRegistry createSchemeRegistry(String url, int port) { SchemeRegistry schemeRegistry = new SchemeRegistry(); String protocol = getProtocol(url); SSLSocketFactory sf; if (HTTP_PROTOCOL.equals(protocol)) { schemeRegistry.register(new Scheme(HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory())); } else if (HTTPS_PROTOCOL.equals(protocol)) { try { if (this.noHostVerification) { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { noCaTrustManager }, null); sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } else { KeyStore truststore = null; InputStream in = null; if (this.keyStorePath != null) { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); try { in = new FileInputStream(this.keyStorePath); truststore.load(in, this.keyStorePassword != null ? this.keyStorePassword.toCharArray() : null); } finally { if (in != null) { in.close(); } } } sf = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, truststore, null, null, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } schemeRegistry.register(new Scheme(HTTPS_PROTOCOL, port, sf)); } catch (NoSuchAlgorithmException e) { throw new SocketFactoryException(NO_TLS_ERROR, e); } catch (KeyManagementException e) { throw new SocketFactoryException(BAD_KEY_ERROR, e); } catch (KeyStoreException e) { throw new SocketFactoryException(KEY_STORE_ERROR, e); } catch (FileNotFoundException e) { throw new SocketFactoryException(KEY_STORE_FILE_NOT_FOUND_ERROR, e); } catch (CertificateException e) { throw new SocketFactoryException(CERTEFICATE_ERROR, e); } catch (IOException e) { throw new SocketFactoryException(IO_ERROR, e); } catch (UnrecoverableKeyException e) { throw new SocketFactoryException(UNRECOVERABLE_KEY_ERROR, e); } } else { throw new ProtocolException(BAD_PROTOCOL_ERROR + protocol); } return schemeRegistry; }
From source file:com.redhat.rcm.version.util.InputUtils.java
private static void setupClient() throws VManException { if (client == null) { SSLSocketFactory sslSocketFactory; try {/*from w w w . jav a2 s .c o m*/ sslSocketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustKs, null, new TrustSelfSignedStrategy(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // sslSocketFactory = // new SSLSocketFactory( SSLSocketFactory.TLS, null, null, trustKs, null, null, // SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER ); } catch (final KeyManagementException e) { logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage()); throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage()); } catch (final UnrecoverableKeyException e) { logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage()); throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage()); } catch (final NoSuchAlgorithmException e) { logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage()); throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage()); } catch (final KeyStoreException e) { logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage()); throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage()); } final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(); ccm.getSchemeRegistry().register(new Scheme("https", 443, sslSocketFactory)); final DefaultHttpClient hc = new DefaultHttpClient(ccm); hc.setRedirectStrategy(new DefaultRedirectStrategy()); final String proxyHost = System.getProperty("http.proxyHost"); final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1")); if (proxyHost != null && proxyPort > 0) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } client = hc; } }
From source file:org.switchyard.component.resteasy.util.ClientInvoker.java
private SSLSocketFactory getSSLSocketFactory(SSLContextModel sslContextConfig) { SSLSocketFactory sslFactory = null; if (sslContextConfig != null) { X509HostnameVerifier verifier = null; if (sslContextConfig.getVerifier() != null) { if (sslContextConfig.getVerifier().equals(ANY)) { verifier = new AllowAllHostnameVerifier(); } else if (sslContextConfig.getVerifier().equals(BROWSER)) { verifier = new BrowserCompatHostnameVerifier(); } else if (sslContextConfig.getVerifier().equals(STRICT)) { verifier = new StrictHostnameVerifier(); }//from ww w . j a v a2s. co m } KeyStore truststore = null; KeyStore keystore = null; if (sslContextConfig.getTruststore() != null) { FileInputStream instream = null; try { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); instream = new FileInputStream(new File(sslContextConfig.getTruststore())); truststore.load(instream, sslContextConfig.getTruststorePass().toCharArray()); } catch (Exception e) { throw RestEasyMessages.MESSAGES.unexpectedExceptionLoadingTruststore(e); } finally { if (instream != null) { try { instream.close(); } catch (IOException ioe) { throw RestEasyMessages.MESSAGES.unexpectedExceptionClosingTruststore(ioe); } } } } if (sslContextConfig.getKeystore() != null) { FileInputStream instream = null; try { keystore = KeyStore.getInstance(KeyStore.getDefaultType()); instream = new FileInputStream(new File(sslContextConfig.getKeystore())); keystore.load(instream, sslContextConfig.getKeystorePass().toCharArray()); } catch (Exception e) { throw RestEasyMessages.MESSAGES.unexpectedExceptionLoadingKeystore(e); } finally { if (instream != null) { try { instream.close(); } catch (IOException ioe) { throw RestEasyMessages.MESSAGES.unexpectedExceptionClosingKeystore(ioe); } } } } try { sslFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keystore, sslContextConfig.getKeystorePass(), truststore, null, verifier); } catch (Exception e) { throw new RuntimeException(e); } } return sslFactory; }
From source file:org.jboss.as.test.manualmode.web.ssl.SSLTruststoreUtil.java
public static DefaultHttpClient getHttpClientWithSSL(File keyStoreFile, String keyStorePassword, File trustStoreFile, String trustStorePassword) { try {// www .ja va2 s . c o m final KeyStore truststore = loadKeyStore(trustStoreFile, trustStorePassword.toCharArray()); final KeyStore keystore = keyStoreFile != null ? loadKeyStore(keyStoreFile, keyStorePassword.toCharArray()) : null; final SSLSocketFactory ssf = new SSLSocketFactory(SSLSocketFactory.TLS, keystore, keyStorePassword, truststore, null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", CustomCLIExecutor.MANAGEMENT_HTTP_PORT, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", CustomCLIExecutor.MANAGEMENT_HTTPS_PORT, ssf)); for (int port : HTTPSWebConnectorTestCase.HTTPS_PORTS) { registry.register(new Scheme("https", port, ssf)); } ClientConnectionManager ccm = new PoolingClientConnectionManager(registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { LOGGER.error( "Creating HttpClient with customized SSL failed. We are returning the default one instead.", e); return new DefaultHttpClient(); } }