Example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

Introduction

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

Prototype

public static void setDefaultHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the default HostnameVerifier inherited by a new instance of this class.

Usage

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

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

    try {//from  ww w .  j  ava2 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

/**
 * Calling to this function we set a HostnameVerifier that always return true
 * accepting any URL although it is different to the certificate
 *//*  w  w w  .j  av a 2 s. com*/
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 w w  w  .  ja  va 2s  . 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:Main.java

static String validGet(URL url) throws IOException {
    String html = "";
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    // TODO ensure HttpsURLConnection.setDefaultSSLSocketFactory isn't
    // required to be reset like hostnames are
    HttpURLConnection conn = null;
    try {/*  w w  w .  j a  va 2s .  c  o m*/
        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        setBasicAuthentication(conn, url);
        int status = conn.getResponseCode();
        if (status != 200) {
            Logd(TAG, "Failed to get from server, returned code: " + status);
            throw new IOException("Get failed with error code " + status);
        } else {
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String decodedString;
            while ((decodedString = br.readLine()) != null) {
                html += decodedString;
            }
            in.close();
        }
    } catch (IOException e) {
        Logd(TAG, "Failed to get from server: " + e.getMessage());
    }
    if (conn != null) {
        conn.disconnect();
    }
    return html;
}

From source file:org.springframework.cloud.contract.wiremock.WireMockSpring.java

public static WireMockConfiguration options() {
    if (!initialized) {
        if (ClassUtils.isPresent("org.apache.http.conn.ssl.NoopHostnameVerifier", null)) {
            HttpsURLConnection.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
            try {
                HttpsURLConnection.setDefaultSSLSocketFactory(SSLContexts.custom()
                        .loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE).build().getSocketFactory());
            } catch (Exception e) {
                Assert.fail("Cannot install custom socket factory: [" + e.getMessage() + "]");
            }// w  w  w .ja v  a 2 s  .  c o  m
        }
        initialized = true;
    }
    WireMockConfiguration config = new WireMockConfiguration();
    config.httpServerFactory(new SpringBootHttpServerFactory());
    return config;
}

From source file:Main.java

public static void trustAllHosts(boolean trustAnyCert, boolean trustAnyHost) {
    try {/*from  ww  w.  ja  v a 2  s  . 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:Main.java

/**
 * Trust every server - dont check for any certificate
 *//*w w w .ja va2 s .  c o  m*/
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub

        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HttpsURLConnection.setDefaultHostnameVerifier(DO_NOT_VERIFY);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
 * General entry point.//from ww  w  .j a  v a  2  s. c om
 * @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:com.lolay.android.security.OpenX509TrustManager.java

public static void openTrust() {
    LolayLog.w(TAG, "openTrust", "THIS IS AN OPEN TRUST MANAGER FOR DEBUGGING ONLY!");
    try {/* ww w  .ja va2  s .co  m*/
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new OpenX509TrustManager() }, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        LolayLog.e(TAG, "openTrust", "Could not open the trust", e);
    }
}

From source file:Main.java

@SuppressWarnings("resource")
public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) {
    Logd(TAG, "Starting post...");
    String html = "";
    Boolean cont = true;//from   w  ww.  ja  va2s . c  o  m
    URL url = null;
    try {
        url = new URL(targetUrl);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Invalid url: " + targetUrl);
        cont = false;
        throw new IllegalArgumentException("Invalid url: " + targetUrl);
    }
    if (cont) {
        if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        } else {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }
            } };
            // Install the all-trusting trust manager
            SSLContext sc;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            } catch (NoSuchAlgorithmException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            } catch (KeyManagementException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            }
        }
        Logd(TAG, "Filename: " + file);
        Logd(TAG, "URL: " + targetUrl);
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        String pathToOurFile = file;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        try {
            connection = (HttpURLConnection) url.openConnection();
            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header)
            //connection.setChunkedStreamingMode(1024);
            // Enable POST method
            connection.setRequestMethod("POST");
            setBasicAuthentication(connection, url);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(connection.getOutputStream());
            //outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> param = iterator.next();
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\""
                        + lineEnd + lineEnd);
                outputStream.write(param.getValue().getBytes("UTF-8"));
                outputStream.writeBytes(lineEnd);
            }
            String connstr = null;
            if (!file.equals("")) {
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\""
                        + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    while (bytesRead > 0) {
                        try {
                            outputStream.write(buffer, 0, bufferSize);
                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            html = "Error: outofmemoryerror";
                            return html;
                        }
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
                fileInputStream.close();
            } else if (data != null) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = data.length;
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    outputStream.write(data, 0, data.length);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    html = "Error: outofmemoryerror";
                    return html;
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
            }
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            Logd(TAG, "Server Response Code " + serverResponseCode);
            Logd(TAG, "Server Response Message: " + serverResponseMessage);
            if (serverResponseCode == 200) {
                InputStreamReader in = new InputStreamReader(connection.getInputStream());
                BufferedReader br = new BufferedReader(in);
                String decodedString;
                while ((decodedString = br.readLine()) != null) {
                    html += decodedString;
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        } catch (Exception ex) {
            // Exception handling
            html = "Error: Unknown error";
            Logd(TAG, "Send file Exception: " + ex.getMessage());
        }
    }
    if (html.startsWith("success:"))
        Logd(TAG, "Server returned: success:HIDDEN");
    else
        Logd(TAG, "Server returned: " + html);
    return html;
}