List of usage examples for javax.net.ssl SSLSession getPeerCertificateChain
@SuppressWarnings("removal") @Deprecated(since = "9", forRemoval = true) public javax.security.cert.X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException;
From source file:Main.java
public static byte[] getEncodedCertificate(SSLSession session) { try {/*from w w w . java 2 s . com*/ return session.getPeerCertificateChain()[0].getEncoded(); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:net.lightbody.bmp.proxy.jetty.http.JsseListener.java
/** * Return the chain of X509 certificates used to negotiate the SSL Session. * <p>//from w w w . j av a2s . c om * Note: in order to do this we must convert a javax.security.cert.X509Certificate[], as used by * JSSE to a java.security.cert.X509Certificate[],as required by the Servlet specs. * * @param sslSession the javax.net.ssl.SSLSession to use as the source of the cert chain. * @return the chain of java.security.cert.X509Certificates used to negotiate the SSL * connection. <br> * Will be null if the chain is missing or empty. */ private static X509Certificate[] getCertChain(SSLSession sslSession) { try { javax.security.cert.X509Certificate javaxCerts[] = sslSession.getPeerCertificateChain(); if (javaxCerts == null || javaxCerts.length == 0) return null; int length = javaxCerts.length; X509Certificate[] javaCerts = new X509Certificate[length]; java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509"); for (int i = 0; i < length; i++) { byte bytes[] = javaxCerts[i].getEncoded(); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); javaCerts[i] = (X509Certificate) cf.generateCertificate(stream); } return javaCerts; } catch (SSLPeerUnverifiedException pue) { return null; } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); return null; } }
From source file:gov.nih.nci.cabig.ccts.security.SecureURL.java
/** * Retrieve the contents from the given URL as a String, assuming the URL's * server matches what we expect it to match. *//*from w ww . ja v a 2 s . c om*/ public static String retrieve(String url) throws IOException { if (log.isTraceEnabled()) { log.trace("entering retrieve(" + url + ")"); } BufferedReader r = null; try { URL u = new URL(url); if (!u.getProtocol().equals("https")) { // IOException may not be the best exception we could throw here // since the problem is with the URL argument we were passed, // not // IO. -awp9 log.error("retrieve(" + url + ") on an illegal URL since protocol was not https."); throw new IOException("only 'https' URLs are valid for this method"); } // JAP: changing to allow validation of Globus-style host names. // URLConnection uc = u.openConnection(); HttpsURLConnection uc = (HttpsURLConnection) u.openConnection(); uc.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { boolean valid = false; try { String expectedHostname = hostname.toLowerCase(); log.debug("expectedHostname = " + expectedHostname); String subjectDN = session.getPeerCertificateChain()[0].getSubjectDN().getName() .toLowerCase(); log.debug("subjectDN = " + subjectDN); String assertedHostname = null; for (String part : subjectDN.split(",")) { String[] nameValue = part.split("="); String name = nameValue[0].toLowerCase().trim(); String value = nameValue[1].trim(); if (name.equals("cn")) { assertedHostname = value; break; } } if (assertedHostname == null) { log.warn("No common name found in subject distinguished name."); return false; } log.debug("assertedHostname = " + assertedHostname); if (assertedHostname.startsWith("host/")) { expectedHostname = "host/" + expectedHostname; log.debug("detected Globus-style common name, expectedHostname = " + expectedHostname); } valid = assertedHostname.equals(expectedHostname); log.debug("valid = " + valid); } catch (Exception ex) { log.warn(ex); } return valid; } }); uc.setRequestProperty("Connection", "close"); r = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = r.readLine()) != null) buf.append(line + "\n"); return buf.toString(); } finally { try { if (r != null) r.close(); } catch (IOException ex) { // ignore } } }
From source file:com.ntsync.android.sync.client.MySSLSocketFactory.java
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException { SSLSession session = socket.getSession(); String hostname = session.getPeerHost(); X509Certificate[] certs = session.getPeerCertificateChain(); if (certs == null || certs.length == 0) { throw new SSLPeerUnverifiedException("No server certificates found!"); }/*w w w. j a va2s . c om*/ // get the servers DN in its string representation String dn = certs[0].getSubjectDN().getName(); // might be useful to print out all certificates we receive from the // server, in case one has to debug a problem with the installed certs. if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Server certificate chain:"); for (int i = 0; i < certs.length; i++) { Log.d(TAG, "X509Certificate[" + i + "]=" + certs[i]); } } // get the common name from the first cert String cn = getCN(dn); if (hostname != null && hostname.equalsIgnoreCase(cn)) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Target hostname valid: " + cn); } } else { if (BuildConfig.DEBUG) { Log.w(TAG, "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'"); return; } throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'"); } }
From source file:com.qpark.eip.core.spring.security.https.EipX509TrustManager.java
/** * <pre>//from w w w . j a v a 2 s . c o m * http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#HostnameVerifier * </pre> * * If the SSL/TLS implementation's standard hostname verification logic * fails, the implementation will call the verify method of the class which * implements this interface and is assigned to this HttpsURLConnection * instance. If the callback class can determine that the hostname is * acceptable given the parameters, it should report that the connection * should be allowed. An unacceptable response will cause the connection to * be terminated. * * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, * javax.net.ssl.SSLSession) */ @Override public boolean verify(final String hostname, final SSLSession session) { try { this.logger.debug("verify hostname={}", hostname); if (hostname != null && session != null && session.getPeerCertificateChain() != null && session.getPeerCertificateChain().length > 0 && session.getPeerCertificateChain()[0] != null && session.getPeerCertificateChain()[0].getPublicKey() != null) { Certificate cert = this.ks.getCertificate(hostname); if (cert != null && cert.getPublicKey() != null) { String ksPublicKey = cert.getPublicKey().toString(); String serverPublicKey = session.getPeerCertificateChain()[0].getPublicKey().toString(); if (ksPublicKey.equals(serverPublicKey)) { return true; } else { this.logger.debug("verify not matching public keys!"); this.logger.debug("verify public key from keystore={}", ksPublicKey); this.logger.debug("verify public key from server ={}", serverPublicKey); } } else { this.logger.debug("verify no cert({}) with PublicKey found.", cert); } } else { this.logger.debug("verify no hostname({}) or session with PeerCertificateChain and PublicKey.", hostname); } } catch (KeyStoreException e) { this.logger.debug("verify {}", e.getMessage()); } catch (SSLPeerUnverifiedException e) { this.logger.debug("verify {}", e.getMessage()); } return false; }
From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.java
/** * Describe <code>verifyHostname</code> method here. * * @param socket a <code>SSLSocket</code> value * @exception SSLPeerUnverifiedException If there are problems obtaining * the server certificates from the SSL session, or the server host name * does not match with the "Common Name" in the server certificates * SubjectDN.//w w w . j a v a 2 s .c o m * @exception UnknownHostException If we are not able to resolve * the SSL sessions returned server host name. */ private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException { if (!verifyHostname) return; SSLSession session = socket.getSession(); String hostname = session.getPeerHost(); try { InetAddress addr = InetAddress.getByName(hostname); } catch (UnknownHostException uhe) { throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname); } X509Certificate[] certs = session.getPeerCertificateChain(); if (certs == null || certs.length == 0) throw new SSLPeerUnverifiedException("No server certificates found!"); //get the servers DN in its string representation String dn = certs[0].getSubjectDN().getName(); //might be useful to print out all certificates we receive from the //server, in case one has to debug a problem with the installed certs. if (LOG.isDebugEnabled()) { LOG.debug("Server certificate chain:"); for (int i = 0; i < certs.length; i++) { LOG.debug("X509Certificate[" + i + "]=" + certs[i]); } } //get the common name from the first cert String cn = getCN(dn); if (hostname.equalsIgnoreCase(cn)) { if (LOG.isDebugEnabled()) { LOG.debug("Target hostname valid: " + cn); } } else { throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'"); } }
From source file:com.app.mvc.http.ext.StrictSSLProtocolSocketFactory.java
/** * Describe <code>verifyHostname</code> method here. * * @param socket a <code>SSLSocket</code> value * @throws SSLPeerUnverifiedException If there are problems obtaining * the server certificates from the SSL session, or the server host name * does not match with the "Common Name" in the server certificates * SubjectDN. * @throws UnknownHostException If we are not able to resolve * the SSL sessions returned server host name. *//*from w w w .jav a 2s .c om*/ private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException { if (!verifyHostname) return; SSLSession session = socket.getSession(); String hostname = session.getPeerHost(); try { InetAddress addr = InetAddress.getByName(hostname); } catch (UnknownHostException uhe) { throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname); } X509Certificate[] certs = session.getPeerCertificateChain(); if (certs == null || certs.length == 0) throw new SSLPeerUnverifiedException("No server certificates found!"); //get the servers DN in its string representation String dn = certs[0].getSubjectDN().getName(); //might be useful to print out all certificates we receive from the //server, in case one has to debug a problem with the installed certs. if (logger.isDebugEnabled()) { logger.debug("Server certificate chain:"); for (int i = 0; i < certs.length; i++) { logger.debug("X509Certificate[" + i + "]=" + certs[i]); } } //get the common name from the first cert String cn = getCN(dn); if (hostname.equalsIgnoreCase(cn)) { if (logger.isDebugEnabled()) { logger.debug("Target hostname valid: " + cn); } } else { throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'"); } }
From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java
/** * Describe <code>verifyHostname</code> method here. * * @param socket a <code>SSLSocket</code> value * @exception SSLPeerUnverifiedException If there are problems obtaining * the server certificates from the SSL session, or the server host name * does not match with the "Common Name" in the server certificates * SubjectDN.//w w w.j a v a 2 s . c o m * @exception UnknownHostException If we are not able to resolve * the SSL sessions returned server host name. */ private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException { if (sslManager == null) { return; } ISSLErrorManager errorMng = sslManager.getSSLErrorManager(); if (errorMng == null) { return; } SSLSession session = socket.getSession(); String hostname = session.getPeerHost(); try { InetAddress.getByName(hostname); } catch (UnknownHostException uhe) { throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname); } X509Certificate[] certs = session.getPeerCertificateChain(); if (certs == null || certs.length == 0) throw new SSLPeerUnverifiedException("No server certificates found!"); //get the servers DN in its string representation String dn = certs[0].getSubjectDN().getName(); //might be useful to print out all certificates we receive from the //server, in case one has to debug a problem with the installed certs. if (LOG.isDebugEnabled()) { LOG.debug("Server certificate chain:"); for (int i = 0; i < certs.length; i++) { LOG.debug("X509Certificate[" + i + "]=" + certs[i]); } } //get the common name from the first cert String cn = getCN(dn); if (hostname.equalsIgnoreCase(cn)) { if (LOG.isDebugEnabled()) { LOG.debug("Target hostname valid: " + cn); } } else { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); java.security.cert.X509Certificate servCert = (java.security.cert.X509Certificate) cf .generateCertificate(new ByteArrayInputStream(certs[0].getEncoded())); if (!errorMng.continueErrorPeer(hostname, servCert)) { throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'"); } } catch (CertificateException ex) { LOG.error(ex.getMessage(), ex); throw new SSLPeerUnverifiedException( "Unexpected error checking HTTPS hostname: " + ex.getMessage()); } catch (CertificateEncodingException ex) { LOG.error(ex.getMessage(), ex); throw new SSLPeerUnverifiedException( "Unexpected error checking HTTPS hostname: " + ex.getMessage()); } } }
From source file:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java
/** * Describe <code>verifyHostname</code> method here. * /* w w w . j a v a 2 s .c o m*/ * @param socket * a <code>SSLSocket</code> value * @exception SSLPeerUnverifiedException * If there are problems obtaining the server certificates from the SSL session, or the server host * name does not match with the "Common Name" in the server certificates SubjectDN. * @exception UnknownHostException * If we are not able to resolve the SSL sessions returned server host name. */ private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException { if (!verifyHostname) return; SSLSession session = socket.getSession(); String hostname = session.getPeerHost(); try { // InetAddress addr = InetAddress.getByName(hostname); InetAddress.getByName(hostname); } catch (UnknownHostException uhe) { throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname); } X509Certificate[] certs = session.getPeerCertificateChain(); if (certs == null || certs.length == 0) throw new SSLPeerUnverifiedException("No server certificates found!"); // get the servers DN in its string representation String dn = certs[0].getSubjectDN().getName(); // might be useful to print out all certificates we receive from the // server, in case one has to debug a problem with the installed certs. if (LOG.isDebugEnabled()) { LOG.debug("Server certificate chain:"); for (int i = 0; i < certs.length; i++) { LOG.debug("X509Certificate[" + i + "]=" + certs[i]); } } // get the common name from the first cert String cn = getCN(dn); if (hostname.equalsIgnoreCase(cn)) { if (LOG.isDebugEnabled()) { LOG.debug("Target hostname valid: " + cn); } } else { throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'"); } }
From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java
/** * Initializes the HTTPs connection/*ww w. ja v a2 s. c om*/ * * @param sslPort * the number of the port the server should be listening for * SSL/TLS connections */ public void InitializeSecure(int sslPort) { if (sslPort != -1) { SSLSocketFactory sslf = null; SSLSocket s = null; port = sslPort; try { // notifyOfProggress(false); KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType()); trusted.load(null, null); sslf = new MySSLSocketFactory(trusted); Log.w("Android mobile voting", "1"); sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Log.w("Android mobile voting", "2"); BasicHttpParams params = new BasicHttpParams(); Log.w("Android mobile voting", "3"); HttpConnectionParams.setConnectionTimeout(params, 500); Log.w("Android mobile voting", "4"); s = (SSLSocket) sslf.connectSocket(sslf.createSocket(), server.getAddress(), sslPort, null, 0, params); if (exc) { SSLSession ssls = null; ssls = s.getSession(); final javax.security.cert.X509Certificate[] x = ssls.getPeerCertificateChain(); for (int i = 0; i < x.length; i++) { parent.mHandler.post(new Runnable() { @Override public void run() { try { parent.askForTrust(getThumbPrint(x[0]), instance); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final Exception ex) { parent.mHandler.post(new Runnable() { @Override public void run() { parent.showToast(ex.toString()); } }); Log.w("Android Mobile Voting", "400 Error"); parent.finish(); } } }); } } s.startHandshake(); Scheme https = new Scheme("https", sslf, sslPort); schemeRegistry.register(https); usingScheme = "https"; port = sslPort; if (!exc) retrieveQuestions(); } catch (final Exception ex) { parent.mHandler.post(new Runnable() { @Override public void run() { parent.showToast(ex.toString()); } }); // Log.w("Android Mobile Voting", "400 Error"); parent.finish(); } } else { parent.mHandler.post(new Runnable() { @Override public void run() { parent.showNoSSLDialog(instance); } }); } }