Java – How to fix SSL exception

Abstract

When you open any connection protected by SSL/TLS (e.g. https), JAVA verify if connection is trusted. If server use self signed certificate or certificate from not know authority JAVA close connection and throws some kind of SSL exception like “javax.net.ssl.SSLHandshakeException”

You can solve this situation by two ways, you can install authority certificate or trust all certificates (disable SSL validation).

[wp_ad_camp_1]

1st. solution – installation of certificate

This is correct solution, if you trust some certificate authority you should add this authority to trusted list.

  1. Download authority certificate (e.g. you can download it from web browser)
  2. Run terminal/cmd as root/administrator
  3. Install certificate to the JRE CA store by command:
keytool -import -trustcacerts -alias AuthorityCA -file authority.crt -storepass changeit -keypass changeit -noprompt -keystore /usr/lib/jvm/java-7-oracle/jre/lib/security/cacerts

Replace “bold” attributes by correct values:

  • AuthorityCA
    certificate alias in keystore
  • authority.crt
    path to downloaded authority certificate
  • changeit
    your password for cacerts storage, “changeit” is default password when you install JAVA
  • /usr/lib/jvm/java-7-oracle/jre/lib/security/cacerts
    path to your file “cacerts” if you use JDK path is “$JAVA_HOME/jre/lib/security/cacerts” if you use JRE path is “$JRE_HOME/lib/security/cacerts”

[wp_ad_camp_1]

 

2nd. solution – disable SSL validation

Important
Use this solution only for development and never in production.

Put lines below to your code. This code have to be run before you create SSL URL, good place is constructor or main method.

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }

    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }
} };

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}

// Now you can access an https URL without having the certificate in the
// truststore
URL url = new URL("https://hostname/index.html");

[wp_ad_camp_1]

Leave a Reply

Your email address will not be published. Required fields are marked *