Example usage for javax.net.ssl HostnameVerifier HostnameVerifier

List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier

Introduction

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

Prototype

HostnameVerifier

Source Link

Usage

From source file:com.fusesource.customer.wssec.client.Main.java

public static void main(String args[]) throws Exception {

    try {//from  w w w  .ja  v a2 s  . co  m
        CommandLine cli = new PosixParser().parse(opts, args);

        timestamp = cli.hasOption("timestamp");
        encrypt = cli.hasOption("encrypt");
        sign = cli.hasOption("sign");
        usernameToken = cli.hasOption("username-token");
        passwordDigest = cli.hasOption("password-digest");
        user = cli.getOptionValue("user");
        pw = cli.getOptionValue("pw");
        disableCNCheck = !cli.hasOption("ecnc");

        if (cli.hasOption("help") || !(sign | encrypt | usernameToken | timestamp)) {
            printUsageAndExit();
        }

        if (sign) {
            sigCertAlias = cli.getOptionValue("sa");
            sigCertPw = cli.getOptionValue("spw");
            sigKsLoc = cli.getOptionValue("sk");
            sigKsPw = cli.getOptionValue("skpw");

            if (sigCertAlias == null || sigKsLoc == null || sigKsPw == null || sigCertPw == null) {
                printUsageAndExit(
                        "You must provide keystore, keystore password, cert alias and cert password for signing certificate");
            }
        }

        if (encrypt) {
            encCertAlias = cli.getOptionValue("ea");
            encKsLoc = cli.getOptionValue("ek");
            encKsPw = cli.getOptionValue("ekpw");

            if (encCertAlias == null || encKsLoc == null || encKsPw == null) {
                printUsageAndExit(
                        "You must provide keystore, keystore password, and cert alias for encryption certificate");
            }
        }

    } catch (ParseException ex) {
        printUsageAndExit();
    }

    // Here we set the truststore for the client - by trusting the CA (in the 
    // truststore.jks file) we implicitly trust all services presenting certificates
    // signed by this CA.
    //
    System.setProperty("javax.net.ssl.trustStore", "../certs/truststore.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "truststore");

    URL wsdl = new URL("https://localhost:8443/cxf/Customers?wsdl");

    // The demo certs provided with this example configure the server with a certificate 
    // called 'fuse-esb'. As this probably won't match the fully-qualified domain
    // name of the machine you're running on, we need to disable Common Name matching
    // to allow the JVM runtime to happily resolve the WSDL for the server. Note that
    // we also have to do something similar on the CXf proxy itself (see below).
    //
    if (disableCNCheck) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        });
    }

    // Initialise the bus
    //
    Bus bus = SpringBusFactory.newInstance().createBus();
    SpringBusFactory.setDefaultBus(bus);

    // Define the properties to configure the WS Security Handler
    //
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(WSHandlerConstants.ACTION, getWSSecActions());

    // Specify the callback handler for passwords.
    //
    PasswordCallback passwords = new PasswordCallback();
    props.put(WSHandlerConstants.PW_CALLBACK_REF, passwords);

    if (usernameToken) {
        passwords.addUser(user, pw);
        props.put(WSHandlerConstants.USER, user);
        props.put(WSHandlerConstants.PASSWORD_TYPE, passwordDigest ? "PasswordDigest" : "PasswordText");
    }

    if (encrypt) {
        props.put(WSHandlerConstants.ENCRYPTION_USER, encCertAlias);
        props.put(WSHandlerConstants.ENC_PROP_REF_ID, "encProps");
        props.put("encProps", merlinCrypto(encKsLoc, encKsPw, encCertAlias));
        props.put(WSHandlerConstants.ENC_KEY_ID, "IssuerSerial");
        props.put(WSHandlerConstants.ENCRYPTION_PARTS, TIMESTAMP_AND_BODY);
    }

    if (sign) {
        props.put(WSHandlerConstants.SIGNATURE_USER, sigCertAlias);
        props.put(WSHandlerConstants.SIG_PROP_REF_ID, "sigProps");
        props.put("sigProps", merlinCrypto(sigKsLoc, sigKsPw, sigCertAlias));
        props.put(WSHandlerConstants.SIG_KEY_ID, "DirectReference");
        props.put(WSHandlerConstants.SIGNATURE_PARTS, TIMESTAMP_AND_BODY);

        passwords.addUser(sigCertAlias, sigCertPw);
    }

    // Here we add the WS Security interceptor to perform security processing
    // on the outgoing SOAP messages. Also, we configure a logging interceptor
    // to log the message payload for inspection. 
    //
    bus.getOutInterceptors().add(new WSS4JOutInterceptor(props));
    bus.getOutInterceptors().add(new LoggingOutInterceptor());

    CustomerService svc = new CustomerService_Service(wsdl).getPort(
            new QName("http://demo.fusesource.com/wsdl/CustomerService/", "SOAPOverHTTP"),
            CustomerService.class);

    // The demo certs provided with this example configure the server with a certificate 
    // called 'fuse-esb'. As this probably won't match the fully-qualified domain
    // name of the machine you're running on, we need to disable Common Name matching
    // to allow the CXF runtime to happily invoke on the server.
    //
    if (disableCNCheck) {
        HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(svc).getConduit();
        TLSClientParameters tls = new TLSClientParameters();
        tls.setDisableCNCheck(true);
        httpConduit.setTlsClientParameters(tls);
    }
    System.out.println("Looking up the customer...");

    // Here's the part where we invoke on the web service. 
    //
    Customer c = svc.lookupCustomer("007");

    System.out.println("Got customer " + c.getFirstName());

}

From source file:Main.java

public static HostnameVerifier createSSLHostnameVerifier(final String apiHostname) {
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override//w  ww  .j a v  a2 s. c o  m
        public boolean verify(String hostname, SSLSession session) {
            //Logcat.d("HostnameVerifier.verify(): " + hostname + " / " + apiHostname);
            return hostname.equals(apiHostname);
        }
    };
    return hostnameVerifier;
}

From source file:Main.java

/**
 * Calling to this function we set a HostnameVerifier that always return true
 * accepting any URL although it is different to the certificate
 *//*from  w w  w.  jav a2s .c  o m*/
public static void acceptDifferentHostnames() {

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });
}

From source file:Main.java

static public void DisableSecurity() throws GeneralSecurityException {
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, new TrustManager[] { new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }/*from   ww w  .  j a  va2s  . c  o  m*/

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    } }, null);

    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse getRequest(String Uri, String requestParameters) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;//from  w  w w  .ja v a  2  s .  c o m
        if (requestParameters != null && requestParameters.length() > 0) {
            urlStr += "?" + requestParameters;
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } catch (IOException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:Main.java

public static void trustAllHosts(boolean trustAnyCert, boolean trustAnyHost) {
    try {//from w  w  w.ja va2s . c  om
        if (trustAnyCert) {
            X509TrustManager easyTrustManager = new X509TrustManager() {

                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };

            // Install the all-trusting trust manager

            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        }

        if (trustAnyHost) {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.rdf4j.http.client.util.HttpClientBuilders.java

/**
 * Return an {@link HttpClientBuilder} that can be used to build an {@link HttpClient} which trusts all
 * certificates (particularly including self-signed certificates).
 * /*from   w w w.j a v a2  s.  c om*/
 * @return a {@link HttpClientBuilder} for <i>SSL trust all</i>
 */
public static HttpClientBuilder getSSLTrustAllHttpClientBuilder() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });

        HostnameVerifier hostNameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);

        return HttpClients.custom().setSSLSocketFactory(sslSF).useSystemProperties();
    } catch (Exception e) {
        // key management exception, etc.
        throw new RuntimeException(e);
    }
}

From source file:net.fenyo.gnetwatch.CommandLine.java

/**
 * General entry point./*from  w w w .j  a va2  s  .  co  m*/
 * @param args command line arguments.
 * @return void.
 * @throws IOException io exception.
 * @throws FileNotFoundException file not found.
 */
public static void main(final String[] args)
        throws IOException, FileNotFoundException, InterruptedException, AlgorithmException {
    Config config = null;
    Synchro synchro = null;
    Background background = null;
    GUI gui = null;
    Main main = null;
    SNMPManager snmp_manager = null;
    CaptureManager capture_mgr = null;

    if (args.length > 0) {
        if (args.length == 4 && args[0].equals("import") && args[1].equals("source")) {
            importGenericSrc(args);
            return;
        }
        log.error("invalid arguments");
        System.exit(1);
    }

    // Get configuration properties
    config = new Config();

    // Set debug level
    // debug level 1: simulate hundreds of ping per second to check the DB and hibernate abilities to handle lots of events
    config.setDebugLevel(0);

    // Read general logging rules
    GenericTools.initLogEngine(config);
    log.info(config.getString("log_engine_initialized"));
    log.info(config.getString("begin"));

    /*
    final MessageBox dialog = new MessageBox(new Shell(new org.eclipse.swt.widgets.Display()),
        SWT.ICON_QUESTION | SWT.YES | SWT.NO);
    // traduire
    dialog.setText("GNetWatch startup");
    dialog.setMessage("Database Selection:\ndo you want to erase the current database content ?");
    dialog.open();
    */

    // Initialize Object-Relational mapping
    synchro = new Synchro(config);

    // Do not check SSL certificates
    SSLContext ssl_context = null;
    try {
        ssl_context = SSLContext.getInstance("SSL");
        ssl_context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
    } catch (final NoSuchAlgorithmException ex) {
        log.error("Exception", ex);
    } catch (final KeyManagementException ex) {
        log.error("Exception", ex);
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(ssl_context.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public final boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    // Initialize background processes management
    background = new Background(config);
    background.createBackgroundThread();

    // Initialize packet capture on every interface
    capture_mgr = new CaptureManager(config);

    // Initialize main processes management
    main = new Main(config, capture_mgr);

    // Build SNMP Manager
    snmp_manager = new SNMPManager();

    // Build GUI
    gui = new GUI(config, background, main, snmp_manager, synchro);
    main.setGUI(gui);
    capture_mgr.setGUI(gui);
    gui.waitForCreation();

    // Initial configuration
    gui.createFromXML(gui.getConfig().getProperty("initialobjects"));

    // Move the GUI to the top of the drawing order
    gui.showGUI();

    // merge events at startup
    background.informQueue("merge-1", gui);

    // Wait for the GUI to terminate
    gui.join();
    // The GUI is now closed
    log.info(config.getString("end"));

    // Stop every application thread
    config.setEnd();
    gui.end();
    background.end();
    capture_mgr.unRegisterAllListeners();

    // stop synchronizing
    synchro.end();
}

From source file:org.jumpmind.symmetric.transport.TransportManagerFactory.java

public static void initHttps(final String httpSslVerifiedServerNames, boolean allowSelfSignedCerts) {
    try {/*from www.  j a v  a  2 s. co  m*/
        if (!StringUtils.isBlank(httpSslVerifiedServerNames)) {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslsession) {
                    boolean verified = false;
                    if (!StringUtils.isBlank(httpSslVerifiedServerNames)) {
                        if (httpSslVerifiedServerNames
                                .equalsIgnoreCase(Constants.TRANSPORT_HTTPS_VERIFIED_SERVERS_ALL)) {
                            verified = true;
                        } else {
                            String[] names = httpSslVerifiedServerNames.split(",");
                            for (String string : names) {
                                if (s != null && s.equals(string.trim())) {
                                    verified = true;
                                    break;
                                }
                            }
                        }
                    }
                    return verified;
                }
            });
        }

        if (allowSelfSignedCerts) {
            HttpsURLConnection.setDefaultSSLSocketFactory(createSelfSignedSocketFactory());
        }

    } catch (GeneralSecurityException ex) {
        throw new SecurityException(ex);
    }

}

From source file:org.wso2.developerstudio.eclipse.platform.ui.utils.SSLUtils.java

/**
 * Initialize the ssl context with the custom trust manager 
 *   1. setup https access to the created ssl context
 *   2. setup hostname verifier//from  w  w  w .  j  a v a2 s.c o  m
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static void init() throws NoSuchAlgorithmException, KeyManagementException {
    if (sslCtx == null) {
        sslCtx = SSLContext.getInstance("SSL");
        sslCtx.init(null, new TrustManager[] { getCustomTrustManager() }, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    }
}