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:test.integ.be.fedict.trust.XKMSTrustTest.java

@Test
public void testValidateUnilateralTLSTrustFail() throws Exception {
    LOG.debug("validate using unilateral TLS Trust, should fail.");

    // Setup/*from w  w  w  . ja  v  a2s.  com*/
    KeyPair keyPair = TestUtils.generateKeyPair();

    /*
     * Override default verification that CN of server SSL certificate has
     * to be equal to the hostname.
     */
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            if (TestUtils.XKMS_WS_HOST.equals(hostname)) {
                return true;
            }
            return false;
        }
    });

    // setup
    List<X509Certificate> signCertificateChain = TestUtils.getSignCertificateChain();
    XKMS2Client client = new XKMS2Client(
            "https://" + TestUtils.XKMS_WS_HOST + ":" + port + TestUtils.XKMS_WS_CONTEXT_PATH);
    client.setServicePublicKey(keyPair.getPublic());

    /*
     * Operate: validate non repudiation
     */
    try {
        client.validate(TrustServiceDomains.BELGIAN_EID_NON_REPUDIATION_TRUST_DOMAIN, signCertificateChain);
        fail();
    } catch (ClientTransportException e) {
        // expected
    }
}

From source file:org.apache.nifi.web.util.WebUtils.java

/**
 * A helper method for creating clients. The client will be created using
 * the given configuration and security context. Additionally, the client
 * will be automatically configured for JSON serialization/deserialization.
 *
 * @param config client configuration/*from ww w .j ava 2  s  .c om*/
 * @param ctx security context, which may be null for non-secure client
 * creation
 *
 * @return a Client instance
 */
private static Client createClientHelper(final ClientConfig config, final SSLContext ctx) {

    final ClientConfig finalConfig = (config == null) ? new DefaultClientConfig() : config;

    if (ctx != null && StringUtils
            .isBlank((String) finalConfig.getProperty(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES))) {

        // custom hostname verifier that checks subject alternative names against the hostname of the URI
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname, final SSLSession ssls) {

                try {
                    for (final Certificate peerCertificate : ssls.getPeerCertificates()) {
                        if (peerCertificate instanceof X509Certificate) {
                            final X509Certificate x509Cert = (X509Certificate) peerCertificate;
                            final List<String> subjectAltNames = CertificateUtils
                                    .getSubjectAlternativeNames(x509Cert);
                            if (subjectAltNames.contains(hostname.toLowerCase())) {
                                return true;
                            }
                        }
                    }
                } catch (final SSLPeerUnverifiedException | CertificateParsingException ex) {
                    logger.warn("Hostname Verification encountered exception verifying hostname due to: " + ex,
                            ex);
                }

                return false;
            }
        };

        finalConfig.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(hostnameVerifier, ctx));
    }

    finalConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    finalConfig.getClasses().add(ObjectMapperResolver.class);

    // web client for restful request
    return Client.create(finalConfig);

}

From source file:com.daoke.mobileserver.test.TestHttps.java

public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
        throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;/*from w w w . ja v a2s  . c  o m*/
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.ssl.SSLSimpleClientHttpRequestFactory.java

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    final HttpURLConnection httpUrlConnection = super.openConnection(url, proxy);
    if (url.getProtocol().toLowerCase().equals("https")) {
        try {// w ww  .ja  v a 2 s . c  om

            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }

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

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[] {};
                }
            } }, null);
            ((HttpsURLConnection) httpUrlConnection).setSSLSocketFactory(ctx.getSocketFactory());
            ((HttpsURLConnection) httpUrlConnection).setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception e) {
        }
    }
    return httpUrlConnection;
}

From source file:org.talend.core.nexus.NexusServerUtils.java

/**
 * // ww w.j  a v  a 2 s.  com
 * DOC check if the repository exist or not
 * 
 * @param nexusUrl
 * @param repositoryId
 * @param userName
 * @param password
 * @return
 */
public static boolean checkConnectionStatus(String nexusUrl, String repositoryId, final String userName,
        final String password) {
    if (StringUtils.isEmpty(nexusUrl)) {
        return false;
    }
    final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator();
    if (userName != null && !"".equals(userName)) {
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password.toCharArray());
            }

        });
    }
    int status = -1;
    try {
        if (nexusUrl == null || "".equals(nexusUrl) || repositoryId == null || "".equals(repositoryId)) {
            return false;
        }
        String newUrl = nexusUrl;
        if (newUrl.endsWith(NexusConstants.SLASH)) {
            newUrl = newUrl.substring(0, newUrl.length() - 1);
        }
        String urlToCheck = newUrl + NexusConstants.CONTENT_REPOSITORIES + repositoryId;

        URL url = new URL(urlToCheck);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            String userDir = Platform.getInstallLocation().getURL().getPath();
            final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory();
            HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
            httpsConnection.setSSLSocketFactory(socketFactory);
            httpsConnection.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

            });
        }
        IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ORG_TALEND_DESIGNER_CORE);
        int timeout = node.getInt(ITalendCorePrefConstants.NEXUS_TIMEOUT, 10000);

        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
        status = urlConnection.getResponseCode();
        if (status == CONNECTION_OK) {
            return true;
        }
    } catch (Exception e) {
        ExceptionHandler.process(e);
    } finally {
        Authenticator.setDefault(defaultAuthenticator);
    }
    return false;
}

From source file:it_minds.dk.eindberetningmobil_android.server.DebugOkHttpStack.java

private static OkHttpClient getUnsafeOkHttpClient(OkHttpClient client) {
    try {/*  www .j ava 2  s .c  om*/
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        client.setSslSocketFactory(sslSocketFactory);
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return client;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ///* w  ww  .ja va2  s . c o m*/
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    b.setSSLContext(sslContext);

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return b;
}

From source file:riddimon.android.asianetautologin.HttpUtils.java

private HttpUtils(Context context) {
    // private constructor to prevent instantiation
    this.context = context;
    try {//w  ww .  j  a va  2s. c  o  m
        // get version number to be set as part of user agent string
        version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
    }
    if (debug) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        try {
            TrustManager[] trustManagers = new X509TrustManager[1];
            trustManagers[0] = new TrustAllManager();

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception ex) {
        }
    }
    // We don't enable response cache because this scenario requires fresh
    // data every time
    //enableHttpResponseCache();
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * {@code connect} is for forming the secure connection between server and
 * android, sending and receiving of the data.
 * /*from  ww  w.ja  v  a 2 s. c om*/
 * @param arg0
 *            data which is to be sent to server.
 * 
 * @return data in string format, received from the server.
 */
public String connect(String... arg0) {

    int nrOfDataToSendToServer = arg0.length;
    nrOfDataToSendToServer = nrOfDataToSendToServer - 1;
    boolean valid = false;
    String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig;

    try {
        //Creating the server certificate
        Certificate serverCertificate = getServerCertificate();

        KeyStore keyStore = getKeyStore(serverCertificate);

        TrustManagerFactory tmf = getTrustManager(keyStore);

        SSLContext sslContext = getSSLContext(tmf);

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier);

        // Converting the data into JSONObject
        JSONObject obj = new JSONObject();
        for (int i = 0; i <= nrOfDataToSendToServer; i++) {
            obj.put("param" + i, arg0[i]);
        }

        // Converting the JSONObject into string
        String dataToSend = obj.toString();

        KeyPairGenerator keyGen = getKeyPairGenerator();

        KeyPair keyPair = keyGen.generateKeyPair();
        //Public key for verifying the digital signature
        PublicKey clientPublicKeySig = keyPair.getPublic();
        //Private key for signing the data
        PrivateKey clientPrivateKeySig = keyPair.getPrivate();

        // Get signed data
        String sigData = getDataSig(clientPrivateKeySig, dataToSend);

        // Creating URL Format
        String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder
                .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8");
        urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "="
                + URLEncoder.encode(dataToSend, "UTF-8");
        urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "="
                + URLEncoder.encode(sigData, "UTF-8");

        // Sending the data to the server
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(urlData);
        wr.flush();
        wr.close();

        // Receiving the data from server
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
            // sb.append(line);
        }
        String text = sb.toString();
        reader.close();

        // Extracting the data, public key and signature received from
        // server
        Vector<String> storeExtractedValues = new Vector<String>();

        storeExtractedValues = extractDataFromJson(text, "data");
        dataFromServer = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig");
        serverPublicKeySigStr = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverDataSig");
        serverDataSig = storeExtractedValues.get(0);

        // Converting the Server Public key format to Java compatible from
        PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr);

        // Verify the received data
        valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig);

        // Disconnect the url connection
        urlConnection.disconnect();

        if (dataFromServer.equalsIgnoreCase("unverified")) {
            CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED;
            return "-1";
        } else if (valid == false) {
            CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED;
            return "-1";
        } else {
            return dataFromServer;
        }

    } catch (Exception e) {
        CExceptionHandling.ExceptionMsg = e.getMessage();

        if (e.toString().equals("java.net.SocketException: Network unreachable")) {
            CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION;
        } else if (e.toString().equals(
                "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) {
            CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT;
        } else {
            CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS;
        }
        return "-1";
    }

}

From source file:org.rhq.plugins.www.util.WWWUtils.java

private static void disableCertificateVerification(HttpsURLConnection connection) {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }//from ww  w  .j  a  va 2s.  com

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

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            return;
        }
    } };
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        connection.setSSLSocketFactory(sslContext.getSocketFactory());
        connection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession sslSession) {
                return true;
            }
        });
    } catch (Exception e) {
        Log log = LogFactory.getLog(WWWUtils.class);
        log.warn("Failed to disable certificate validation.", e);
    }
}