One problem people have with Java and SSL is that the certificate manager will reject any self signed certificates.
This is common when you are doing development or are using an internal certificate that you don't want to pay money for from a commercial certificate authority.
One way to handle this is to simply accept any certificate, regardless of what it has in it. Below is a simple program to do just that, it reads a URL and, regardless of what the certificate says, prints out the contents of the URL.
package com.xigole.util.ssl;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SelfSignedCertTest {
public static void main(String[] argv) {
if (argv.length != 1) {
System.err.println("usage: SelfSignedCertTest hostname");
System.exit(1);
}
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) {
System.out.println("authType is " + authType);
System.out.println("cert issuers");
for (int i = 0; i < certs.length; i++) {
System.out.println("\t" + certs[i].getIssuerX500Principal().getName());
System.out.println("\t" + certs[i].getIssuerDN().getName());
}
}
} };
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
URL url = null;
try {
url = new URL("https", argv[0], 443, "/");
} catch (MalformedURLException mue) {
mue.printStackTrace();
System.exit(1);
}
try {
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1)
System.out.println(new String(buffer, 0, bytesRead));
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}
}
}
Greetings.
Daniel