Automated SSL Certificate Renewal and Installation

Something like this seems like it would work:

import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

public class CertVerify {
    public static void main(String[] args) {
        try {
            String expectedSerialNumber = "";
            String CN = "";
            String url = String.format("https://%s:8043", CN);
            URL destinationUrl = new URL (url);
            HttpsURLConnection conn = (HttpsURLConnection) destinationUrl.openConnection();
            conn.connect();
            Certificate[] certs = conn.getServerCertificates();

            for (Certificate cert : certs) {
                if (cert instanceof X509Certificate) {
                    String DN = ((X509Certificate) cert).getSubjectDN().toString();
                    if(DN.contains(CN)) {
                        System.out.println(DN);
                        System.out.println("Expires: " + ((X509Certificate) cert).getNotAfter());
                        String SN = ((X509Certificate) cert).getSerialNumber().toString();
                        System.out.println(SN);
                        Boolean matches = SN.equals(expectedSerialNumber);
                        System.out.println("Cert Serial Number matches expected value: " + matches);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getCause());
        }


    }
}

3 Likes