We help IT Professionals succeed at work.
Get Started

Check for SSL Certificates Before Connection

onaled777
onaled777 asked
on
97 Views
Last Modified: 2016-01-13
This method that I wrote seems to throw an error at "con.getResponseCode()" whenever the server certificates are not configured correctly


	private static String sendGetHttps(String url) 
	{
		BufferedReader in = null;
		try{
			logger.info("Connecting to url: " + url);
			URL obj = new URL(url);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

			con.setRequestMethod("GET");
			int responseCode = con.getResponseCode(); 
			logger.info("Response Code after connecting to url: " + responseCode);
			in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			logger.info("Response String: " + response.toString());
			
			return response.toString();
		}catch(Exception e ){
			throw new PMRException(e.getMessage(),e);
		}
		finally
		{
			if(in!= null)
			{
				try
				{
					in.close();
				}
				catch(Exception e)
				{
				
				}
			}
		}
	}

Open in new window



To configure them I call this method before the one above:
	public static void getSSLCertificate(String keyStoreLocation, String keyStorePassword, String jksPassword) {
		
		final char[] JKS_PASSWORD = jksPassword.toCharArray();
		final char[] KEY_PASSWORD = keyStorePassword.toCharArray();
		
		try {
			
			// Get the JKS contents 
			final KeyStore keyStore = KeyStore.getInstance("JKS");
			keyStore.load(new FileInputStream(new File(keyStoreLocation)), JKS_PASSWORD);
			final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(keyStore, KEY_PASSWORD);
			final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			tmf.init(keyStore);
			
			 // Creates a socket factory for HttpsURLConnection using JKS contents
			final SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom());
			final SSLSocketFactory socketFactory = sc.getSocketFactory();
			HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
			
		} catch (IOException exc) {
			throw new RuntimeException(exc);
		} catch (GeneralSecurityException e) {
			throw new RuntimeException(e);
		}
	}

Open in new window


The problem that I am having is that if the second method is not called before the first, then the certificates are not in place and I get this error:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)

Open in new window


Of course when I call the methods in the right order that error is not there.

My question is can anyone help me write a check that can be done on maybe the HttpsURLConnection con object from the first code that can help me verify that the relevant certificates are properly recognized? Of course, the aim is to find a a more graceful way to exit when there is an error.

A sample test that was written is as follows:
public class ProgramTest {
	public static void main(String[] args){
		try {
			NetUtils.getSSLCertificate("c:/Users/kingw/.keystore", "changeit", "changeit"); 
			NetUtils.sendGet("https://testing.dev.cfed.local/api/auth/" + "c076utf5-2aaa-4b58-92d3-981dyhfefvgyyh" + "/" + "22");
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
}

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Distinguished Expert 2020
Commented:
This problem has been solved!
Unlock 1 Answer and 8 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE