Java‎ > ‎

SSL

SSL connectivity, ignoring CertificateException, thrown for expired or self-signed certificates.

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) {}
        }
};
int port = 443;
String host = "10.0.0.1";

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
//Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
//SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocketFactory factory =sc.getSocketFactory();
SSLSocket s = (SSLSocket) factory.createSocket(host, port);

InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();

For HTTPS request against a server with an invalid certificate:
package info.compute.example;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class InsecureSSLGet {
public static void main(String[] args) {
BufferedReader in = null;
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) {}
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new TestHostnameVerifier());
URL exampleConn = new URL("https://secure.compute.info/");
URLConnection bld = exampleConn.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(bld.getInputStream()));

                        String line;

                        
while((line = br.readLine()) != null)

                            System.out.println(line);

                        br.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}

class TestHostnameVerifier implements HostnameVerifier {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
}








Comments