Search code examples
javasslhttpsocspcertificate-revocation

How can we do our own Certificate Verification Step in HTTPS


I need to put my own certificate verification step in SSL Handshake when making an HTTPS connection with HttpsURLConnection. I have written my own certificate verification code to verify some property in the host certificates say Certificate Revocation Status using Online Certificate Status Protocol. What is the proper way to include this step in Java. I can add it as a part of the default HostNameVerifier as follows but is there a proper way to do this?

HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
        public boolean verify(String s, SSLSession sslSession) {
            return verifier.verify(s, sslSession) && MyVerifier.doMyVerification(sslSession);
        }
    }); 

Solution

  • Figured out a cleaner way. Can use our own TrustManager to do the custom certificate verification. Here is the code,

    public class Test {
    
    
    public static void main(String [] args) throws Exception {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
        SSLContext.setDefault(ctx);
    
        URL url = new URL("https://www.google.com");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        System.out.println(conn.getResponseCode());
        conn.disconnect();
    }
    
    private static class DefaultTrustManager implements X509TrustManager {
    
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }
    
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            //Do certificate verification here and throw exception if invalid
            throw new CertificateException();
        }
    
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
    
    }