Java Code Examples for javax.net.ssl.HttpsURLConnection#getServerCertificates()

The following examples show how to use javax.net.ssl.HttpsURLConnection#getServerCertificates() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Connection.java    From J2ME-Loader with Apache License 2.0 6 votes vote down vote up
@Override
public SecurityInfo getSecurityInfo() throws IOException {
	if (securityInfo == null) {
		if (cn == null) {
			throw new IOException();
		}
		if (!connected) {
			cn.connect();
			connected = true;
		}
		HttpsURLConnection https = (HttpsURLConnection) cn;

		Certificate[] certs = https.getServerCertificates();
		if (certs.length == 0) {
			throw new IOException();
		}
		securityInfo = new SecurityInfoImpl(
				https.getCipherSuite(),
				sslContext.getProtocol(),
				new CertificateImpl((X509Certificate) certs[0]));
	}

	return securityInfo;
}
 
Example 2
Source File: ExprUrlSSLSerialNumber.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected String[] get(Event e) {
  try {
    HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.connect();
    for (Certificate cert : c.getServerCertificates()) {
      if (cert instanceof X509Certificate) {
        c.disconnect();
        X509Certificate sc = (X509Certificate) cert;
        return new String[]{sc.getSerialNumber().toString(16)};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 3
Source File: ExprUrlSSLIssueExpire.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected Number[] get(Event e) {
  try {
    HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.connect();
    for (Certificate cert : c.getServerCertificates()) {
      if (cert instanceof X509Certificate) {
        c.disconnect();
        X509Certificate sc = (X509Certificate) cert;
        String sv;
        if (ty == 0) {
          sv = String.valueOf(sc.getNotBefore().getTime());
        } else {
          sv = String.valueOf(sc.getNotAfter().getTime());
        }
        return new Number[]{Long.parseLong(sv.substring(0, 10))};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 4
Source File: ExprUrlSSLVersion.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected Number[] get(Event e) {
  try {
    HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.connect();
    for (Certificate cert : c.getServerCertificates()) {
      if (cert instanceof X509Certificate) {
        c.disconnect();
        X509Certificate sc = (X509Certificate) cert;
        return new Number[]{sc.getVersion()};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 5
Source File: ExprUrlSSLVerifier.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected String[] get(Event e) {
  try {
    HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.connect();
    for (Certificate cert : c.getServerCertificates()) {
      if (cert instanceof X509Certificate) {
        c.disconnect();
        X509Certificate sc = (X509Certificate) cert;
        String[] s = sc.getIssuerX500Principal().getName().split("O=");
        s = s[1].split(",C");
        return new String[]{s[0]};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 6
Source File: ExprUrlSSLAlgorithm.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected String[] get(Event e) {
  try {
    HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.connect();
    for (Certificate cert : c.getServerCertificates()) {
      if (cert instanceof X509Certificate) {
        c.disconnect();
        X509Certificate sc = (X509Certificate) cert;
        return new String[]{sc.getSigAlgName()};
      }
    }
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 7
Source File: StatusCheckerTimer.java    From oxTrust with MIT License 6 votes vote down vote up
private void setCertificateExpiryAttributes(ConfigurationStatus configuration) {
	try {
		URL destinationURL = new URL(appConfiguration.getApplicationUrl());
		HttpsURLConnection conn = (HttpsURLConnection) destinationURL.openConnection();
		conn.connect();
		Certificate[] certs = conn.getServerCertificates();
		if (certs.length > 0) {
			if (certs[0] instanceof X509Certificate) {
				X509Certificate x509Certificate = (X509Certificate) certs[0];
				Date expirationDate = x509Certificate.getNotAfter();
				long expiresAfter = TimeUnit.MILLISECONDS.toDays(expirationDate.getTime() - new Date().getTime());
				configuration.setSslExpiry(toIntString(expiresAfter));
			}
		}
	} catch (IOException e) {
		log.error("Can not download ssl certificate", e);
	}
}
 
Example 8
Source File: HttpResponseCache.java    From cordova-android-chromeview with Apache License 2.0 6 votes vote down vote up
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  if (isHttps()) {
    HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
    cipherSuite = httpsConnection.getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = httpsConnection.getServerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = httpsConnection.getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
Example 9
Source File: HttpResponseCache.java    From cordova-android-chromeview with Apache License 2.0 6 votes vote down vote up
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  if (isHttps()) {
    HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
    cipherSuite = httpsConnection.getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = httpsConnection.getServerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = httpsConnection.getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
Example 10
Source File: HttpResponseCache.java    From phonegap-plugin-loading-spinner with Apache License 2.0 6 votes vote down vote up
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  if (isHttps()) {
    HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
    cipherSuite = httpsConnection.getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = httpsConnection.getServerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = httpsConnection.getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
Example 11
Source File: HttpResponseCache.java    From phonegap-plugin-loading-spinner with Apache License 2.0 6 votes vote down vote up
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  if (isHttps()) {
    HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
    cipherSuite = httpsConnection.getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = httpsConnection.getServerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = httpsConnection.getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
Example 12
Source File: CertificateChain.java    From Hands-On-Cryptography-with-Java with MIT License 5 votes vote down vote up
public static void main(String[] args) throws MalformedURLException, IOException, CertificateNotYetValidException {
    URL url = new URL("https://www.packtpub.com");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.connect();
    Certificate[] certs = conn.getServerCertificates();

    Arrays.stream(certs).forEach(CertificateChain::printCert);

    System.out.println("There are " + certs.length + " certificates.");
    Arrays.stream(certs).map(cert -> (X509Certificate) cert)
            .forEach(x509 -> System.out.println(x509.getIssuerDN().getName()));
    System.out.println("The final certificate is for: " + conn.getPeerPrincipal());
}
 
Example 13
Source File: JCurl.java    From JCurl with Apache License 2.0 5 votes vote down vote up
private void processResponseCertificates(HttpURLConnection con, Response response) throws SSLPeerUnverifiedException {
  if (con instanceof HttpsURLConnection) {
    try {
      HttpsURLConnection secureConn = (HttpsURLConnection) con;
      response.cipherSuite = secureConn.getCipherSuite();
      response.serverCertificates = secureConn.getServerCertificates();
      response.clientCertificates = secureConn.getLocalCertificates();
    } catch (IllegalStateException e) {
      // If the response is not a 200, getting response certificates will fail with the (misleading) message
      // "connection not yet open". Ignore this.
    }
  }
}
 
Example 14
Source File: HttpsURLConnectionInfo.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * This constructor is used to create the info object
 * representing the this HttpsURLConnection. Connection parameter is
 * of supertype HttpURLConnection, which allows internal cast to
 * potentially divergent subtype (Https) implementations.
 */
public HttpsURLConnectionInfo(HttpURLConnection connection)
    throws IOException {
    super(connection.getURL(), connection.getRequestMethod());
    if (connection instanceof HttpsURLConnection) {
        HttpsURLConnection conn = (HttpsURLConnection) connection;
        enabledCipherSuite = conn.getCipherSuite();
        localCertificates = conn.getLocalCertificates();
        localPrincipal = conn.getLocalPrincipal();
        serverCertificates = conn.getServerCertificates();
        peerPrincipal = conn.getPeerPrincipal();
    } else {
        Exception ex = null;
        try {
            Method method = null;
            method = connection.getClass().getMethod("getCipherSuite", (Class[]) null);
            enabledCipherSuite = (String) method.invoke(connection, (Object[]) null);
            method = connection.getClass().getMethod("getLocalCertificates", (Class[]) null);
            localCertificates = (Certificate[]) method.invoke(connection, (Object[]) null);
            method = connection.getClass().getMethod("getServerCertificates", (Class[]) null);
            serverCertificates = (Certificate[]) method.invoke(connection, (Object[]) null);

            //TODO Obtain localPrincipal and peerPrincipal using the com.sun.net.ssl api
        } catch (Exception e) {
            ex = e;
        } finally {
            if (ex != null) {
                if (ex instanceof IOException) {
                    throw (IOException) ex;
                }
                IOException ioe = new IOException("Error constructing HttpsURLConnectionInfo "
                                                  + "for connection class "
                                                  + connection.getClass().getName());
                ioe.initCause(ex);
                throw ioe;

            }
        }
    }
}
 
Example 15
Source File: HttpUtils.java    From mclauncher-api with MIT License 5 votes vote down vote up
/**
 * Execute a secured POST request
 * @param url URL to request
 * @param keyInput the secret key to be used
 * @param parameters Parameters in form <code>name=Tom&amp;password=pass123</code>. They needn't to be URL-encoded(it will be done automatically)
 * @return The result of request
 * @throws Exception I/O Exception, HTTP errors or invalid key
 */
public static String securePostWithKey(String url, InputStream keyInput, String parameters) throws Exception {
    URL u = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) u.openConnection();
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("Content-Length", "" + parameters.getBytes().length);
    connection.setRequestProperty("Content-Language", "en-US");

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

    connection.connect();
    Certificate cert = connection.getServerCertificates()[0];
    byte[] serverKey = cert.getPublicKey().getEncoded();
    DataInputStream dis = new DataInputStream(keyInput);
    for (int i = 0; i < serverKey.length; ++i) {
        if (dis.readByte() != serverKey[i]) {
            throw new SecurityException("Invalid Server Key!");
        }
    }
    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
    dos.writeBytes(URLEncoder.encode(parameters, "utf-8"));
    dos.flush();
    dos.close();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = br.readLine()) != null) {
        response = response.append(line).append('\r');
    }
    br.close();
    connection.disconnect();
    return response.toString();
}
 
Example 16
Source File: CipherSuiteUtil.java    From DeepViolet with Apache License 2.0 3 votes vote down vote up
/**
 * Retrieve a certificate chain based upon URL.  Note this API will return
 * certificates with unvalidated and possibly bad trust chains.
 * @param url Target URL
 * @return X509Certificate Certificate chain
 * @throws Exception Thrown on problems.
 * @see <a href="http://stackoverflow.com/questions/19723415/java-overriding-function-to-disable-ssl-certificate-check">java-overriding-function-to-disable-ssl-certificate-check</a>
 */
static final X509Certificate[] getServerCertificateChain(URL url) throws Exception {

       ArrayList<X509Certificate> list = new ArrayList<X509Certificate>();
	
	try {
		
		enableTLSChainTesting(false);
		
        HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
        conn.connect();
        Certificate[] certs = conn.getServerCertificates();
        
        for (Certificate cert : certs) {
        	
            if(cert instanceof X509Certificate) {            	
            	list.add( (X509Certificate)cert );           
            } else {
            	logger.info("Unsupported certificate type.  type="+cert.getClass().getName());
            }
        }
        
	} finally {
		
		enableTLSChainTesting(true);
		
	}

       return list.toArray(new X509Certificate[0]);
}