Example usage for javax.net.ssl HttpsURLConnection getServerCertificates

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

Introduction

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

Prototype

public abstract java.security.cert.Certificate[] getServerCertificates() throws SSLPeerUnverifiedException;

Source Link

Document

Returns the server's certificate chain which was established as part of defining the session.

Usage

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

static void checkServerCertsExpirationDays(Configuration conf, String hostname, int port) throws IOException {
    setupSslProps(conf);/*from  ww  w .  j a  va2s  .  c o m*/
    HttpsURLConnection connection = null;
    connection = openConnection(hostname, port, null);
    connection.connect();
    X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates();
    Date curDate = new Date();
    long curTime = curDate.getTime();
    if (serverCerts != null) {
        for (X509Certificate cert : serverCerts) {
            StringBuffer sb = new StringBuffer();
            sb.append("\n Server certificate Subject Name: " + cert.getSubjectX500Principal().getName());
            Date expDate = cert.getNotAfter();
            long expTime = expDate.getTime();
            int dayOffSet = (int) ((expTime - curTime) / MM_SECONDS_PER_DAY);
            sb.append(" have " + dayOffSet + " days to expire");
            if (dayOffSet < CERT_EXPIRATION_WARNING_THRESHOLD)
                LOG.warn(sb.toString());
            else
                LOG.info(sb.toString());
        }
    } else {
        LOG.info("\n No Server certs was found");
    }

    if (connection != null) {
        connection.disconnect();
    }
}

From source file:Main.java

public static String executeHttpsPost(String url, String data, InputStream key) {
    HttpsURLConnection localHttpsURLConnection = null;
    try {/*w  ww.j av a 2 s  .  c o m*/
        URL localURL = new URL(url);
        localHttpsURLConnection = (HttpsURLConnection) localURL.openConnection();
        localHttpsURLConnection.setRequestMethod("POST");
        localHttpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        localHttpsURLConnection.setRequestProperty("Content-Length",
                "" + Integer.toString(data.getBytes().length));
        localHttpsURLConnection.setRequestProperty("Content-Language", "en-US");

        localHttpsURLConnection.setUseCaches(false);
        localHttpsURLConnection.setDoInput(true);
        localHttpsURLConnection.setDoOutput(true);

        localHttpsURLConnection.connect();
        Certificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates();

        byte[] arrayOfByte1 = new byte[294];
        DataInputStream localDataInputStream = new DataInputStream(key);
        localDataInputStream.readFully(arrayOfByte1);
        localDataInputStream.close();

        Certificate localCertificate = arrayOfCertificate[0];
        PublicKey localPublicKey = localCertificate.getPublicKey();
        byte[] arrayOfByte2 = localPublicKey.getEncoded();

        for (int i = 0; i < arrayOfByte2.length; i++) {
            if (arrayOfByte2[i] != arrayOfByte1[i])
                throw new RuntimeException("Public key mismatch");
        }

        DataOutputStream localDataOutputStream = new DataOutputStream(
                localHttpsURLConnection.getOutputStream());
        localDataOutputStream.writeBytes(data);
        localDataOutputStream.flush();
        localDataOutputStream.close();

        InputStream localInputStream = localHttpsURLConnection.getInputStream();
        BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));

        StringBuffer localStringBuffer = new StringBuffer();
        String str1;
        while ((str1 = localBufferedReader.readLine()) != null) {
            localStringBuffer.append(str1);
            localStringBuffer.append('\r');
        }
        localBufferedReader.close();

        return localStringBuffer.toString();
    } catch (Exception localException) {
        byte[] arrayOfByte1;
        localException.printStackTrace();
        return null;
    } finally {
        if (localHttpsURLConnection != null)
            localHttpsURLConnection.disconnect();
    }
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

static boolean sendCommand(Configuration conf, String path) throws IOException {
    setupSslProps(conf);/*  ww  w  . j  a v  a  2 s  . c o  m*/
    int sslPort = getSslAddr(conf).getPort();
    int err = 0;
    StringBuilder b = new StringBuilder();

    HostsFileReader hostsReader = new HostsFileReader(conf.get("hdfsproxy.hosts", "hdfsproxy-hosts"), "");
    Set<String> hostsList = hostsReader.getHosts();
    for (String hostname : hostsList) {
        HttpsURLConnection connection = null;
        try {
            connection = openConnection(hostname, sslPort, path);
            connection.connect();
            if (LOG.isDebugEnabled()) {
                StringBuffer sb = new StringBuffer();
                X509Certificate[] clientCerts = (X509Certificate[]) connection.getLocalCertificates();
                if (clientCerts != null) {
                    for (X509Certificate cert : clientCerts)
                        sb.append("\n Client certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No client certificates were found");
                }
                X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates();
                if (serverCerts != null) {
                    for (X509Certificate cert : serverCerts)
                        sb.append("\n Server certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No server certificates were found");
                }
                LOG.debug(sb.toString());
            }
            if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
                b.append("\n\t" + hostname + ": " + connection.getResponseCode() + " "
                        + connection.getResponseMessage());
                err++;
            }
        } catch (IOException e) {
            b.append("\n\t" + hostname + ": " + e.getLocalizedMessage());
            if (LOG.isDebugEnabled())
                LOG.debug("Exception happend for host " + hostname, e);
            err++;
        } finally {
            if (connection != null)
                connection.disconnect();
        }
    }
    if (err > 0) {
        System.err.print("Command failed on the following " + err + " host" + (err == 1 ? ":" : "s:")
                + b.toString() + "\n");
        return false;
    }
    return true;
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testValidation() throws Exception {
    Proxy proxy = Proxy.NO_PROXY;
    // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
    // "proxy.yourict.net", 8080));
    NetworkConfig networkConfig = null; // new
    // NetworkConfig("proxy.yourict.net",
    // 8080);/* ww  w  . j a  v a2 s  . c om*/
    // URL url = new URL("https://eid.belgium.be/"); // OK
    // URL url = new URL("https://www.fortisbanking.be"); // OK
    // URL url = new URL("https://www.e-contract.be/"); // OK
    // URL url = new URL("https://idp.services.belgium.be"); // OK
    // URL url = new URL("https://idp.int.belgium.be"); // OK
    //URL url = new URL("https://test.eid.belgium.be/");
    URL url = new URL("https://www.cloudflare.com/");

    // URL url = new URL("https://www.facebook.com");
    // URL url = new URL("https://www.twitter.com");
    // URL url = new URL("https://www.mozilla.org");
    // URL url = new URL("https://www.verisign.com/");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
    connection.connect();
    Certificate[] serverCertificates = connection.getServerCertificates();
    List<X509Certificate> certificateChain = new LinkedList<>();
    for (Certificate certificate : serverCertificates) {
        X509Certificate x509Cert = (X509Certificate) certificate;
        certificateChain.add(x509Cert);
        LOG.debug("certificate subject: " + x509Cert.getSubjectX500Principal());
        LOG.debug("certificate issuer: " + x509Cert.getIssuerX500Principal());
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCertificate = (X509Certificate) certificateFactory.generateCertificate(
            SSLTrustValidatorTest.class.getResourceAsStream("/ecc/AddTrustExternalCARoot.crt"));
    certificateChain.add(rootCertificate);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(certificateChain.get(certificateChain.size() - 1));

    //certificateRepository.addTrustPoint(rootCertificate);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);
    trustValidator.setAlgorithmPolicy(new AlgorithmPolicy() {

        @Override
        public void checkSignatureAlgorithm(String signatureAlgorithm, Date validationDate)
                throws SignatureException {
            LOG.debug("signature algo: " + signatureAlgorithm);
            // allow all
        }
    });

    // next is kind of a default trust linked pattern.
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);

    // operate
    trustValidator.isTrusted(certificateChain);
}

From source file:com.ct855.util.HttpsClientUtil.java

private void print_https_cert(HttpsURLConnection con) {

    if (con != null) {

        try {//from  ww w .  j  av a 2s. com

            System.out.println("Response Code : " + con.getResponseCode());
            System.out.println("Cipher Suite : " + con.getCipherSuite());
            System.out.println("\n");

            Certificate[] certs = con.getServerCertificates();
            for (Certificate cert : certs) {
                System.out.println("Cert Type : " + cert.getType());
                System.out.println("Cert Hash Code : " + cert.hashCode());
                System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
                System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
                System.out.println("\n");
            }

        } catch (SSLPeerUnverifiedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

From source file:com.aivarsda.certpinninglib.HttpsPinner.java

/**
 * Will go over all certificate chains of the given HttpsURLConnection and
 * validate each one./*www .j  ava2 s. c o  m*/
 * 
 * @param con HttpsURLConnection that needs to be pinned.
 */
private boolean validateTrustedPins(HttpsURLConnection con) {
    boolean isSrvTrusted = false;
    if (con != null) {
        try {
            Certificate[] certs = con.getServerCertificates();
            for (Certificate cert : certs) {
                // More info on X509Certificate -> http://www.ietf.org/rfc/rfc2459.txt
                if (cert instanceof X509Certificate) {
                    // Checking the certificate validity, if not valid - exception will be thrown.
                    ((X509Certificate) cert).checkValidity();

                    // Pinning the certificate against the trusted pins list.
                    boolean hasTrustedPin = false;
                    try {
                        hasTrustedPin = hasTrustedPin((X509Certificate) cert);
                        if (hasTrustedPin)
                            isSrvTrusted = true;
                    } catch (CertificateException e) {
                        Log.e(TAG, e.toString());
                    }

                    // Stop when the trusted pin is found
                    if (hasTrustedPin && _stopPinningWhenTrusdedFound)
                        break;
                }
            }
        } catch (SSLPeerUnverifiedException e) {
            Log.e(TAG, e.toString());
        } catch (CertificateExpiredException e1) {
            Log.e(TAG, e1.toString());
        } catch (CertificateNotYetValidException e1) {
            Log.e(TAG, e1.toString());
        }
    }

    return isSrvTrusted;
}

From source file:com.mhise.util.MHISEUtil.java

public static KeyStore getServerKeyStore(String url) {
    KeyStore ks = null;/*from   w ww. ja v a 2 s.co m*/
    try {
        MHISETrustManager.allowAllSSL();
        HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection();

        connection.connect();

        Certificate[] certs = connection.getServerCertificates();
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setCertificateEntry("servercert", certs[0]);
        Log.i("MHISEUtil-->getServerKeyStore", certs[0].getPublicKey().toString());
    } catch (Exception e) {

        Logger.debug("MHISEUtil-->getServerKeyStore", "Exception" + e);
        e.printStackTrace();
    }
    return ks;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Returns the certificate chain provided by the HTTPS server.
 *
 * The first certificate identifies the server.
 * The remainder should verify the cert upto a trusted root.
 *
 *
 * @param url//from   w  w  w  . j ava 2s .  c om
 * @return
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
public List<X509Certificate> getCertHttps(URL url)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {
    ArrayList<X509Certificate> toReturn = new ArrayList<>();

    // Setup a temp ssl context that accepts all certificates for this connection
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        private X509Certificate[] certToReturn;

        @Override
        public void checkClientTrusted(X509Certificate[] c, String s) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] c, String s) {
            certToReturn = c;
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return certToReturn;
        }
    } }, null);

    //Setup a temp hostname verifier that verifies all hostnames for this connection
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession ss) {
            return true;
        }
    };
    HttpsURLConnection httpsConn = null;
    try {
        httpsConn = (HttpsURLConnection) url.openConnection();

        httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
        httpsConn.setHostnameVerifier(hv);
        httpsConn.connect();

        Certificate[] certs = httpsConn.getServerCertificates();

        for (Certificate cert : certs) {
            if (cert instanceof X509Certificate) {
                toReturn.add((X509Certificate) cert);
            }
        }
    } finally {
        if (httpsConn != null) {
            httpsConn.disconnect();
        }
    }
    return toReturn;
}

From source file:it.jnrpe.plugin.CheckHttp.java

private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception {
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
    SSLContext.setDefault(ctx);//from   www  . j a v  a2 s .co m
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    });
    List<Date> expiryDates = new ArrayList<Date>();
    conn.getResponseCode();
    Certificate[] certs = conn.getServerCertificates();
    for (Certificate cert : certs) {
        X509Certificate x509 = (X509Certificate) cert;
        Date expiry = x509.getNotAfter();
        expiryDates.add(expiry);
    }

    conn.disconnect();
    Date today = new Date();
    for (Date date : expiryDates) {
        int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
        metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null));
    }
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private String getPEMCertificateFromServer(String host) {
    HttpsURLConnection connection = null;
    try {/* w w w  . java 2s  .co m*/
        URL url = new URL(host);

        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(hostnameVerifier);
        connection.setSSLSocketFactory(generateSSLContextWhichAcceptAllSSLCertificats());
        connection.connect();

        java.security.cert.Certificate[] cert = connection.getServerCertificates();
        connection.disconnect();

        byte[] by = ((X509Certificate) cert[0]).getEncoded();
        if (by.length != 0) {
            return BEGIN_CERT + Base64.getEncoder().encodeToString(by) + END_CERT;
        }
    } catch (MalformedURLException e) {
        if (!informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION)) {
            logger.error("A MalformedURLException occurred: ", e);
        }
    } catch (IOException e) {
        short code = ConnectionManager.GENERAL_EXCEPTION;
        if (e instanceof java.net.ConnectException) {
            code = ConnectionManager.CONNECTION_EXCEPTION;
        } else if (e instanceof java.net.UnknownHostException) {
            code = ConnectionManager.UNKNOWN_HOST_EXCEPTION;
        }
        if (!informConnectionManager(code) || code == -1) {
            logger.error("An IOException occurred: ", e);
        }
    } catch (CertificateEncodingException e) {
        logger.error("A CertificateEncodingException occurred: ", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}