Monday, July 3, 2017

Get SSL Certificates expiration dates using Simple Java Code

I have been looking for neat solution to find out the expiration dates for WebLogic Server using SSL Certificates in a given Java KeyStore, The limitation with Unix and Python scripts would be that we will end up working with the string value that Java keytool Utility returns.
After several trials to be more effective, I believe it is better to do this using Java Code.
So below snippet would be of some help to those who are looking for similar thing.

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Enumeration;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.security.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.*;

public class sslcertsExpirydates_2 {

public static void main(String[] argv) throws Exception {

 try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(new FileInputStream("/u01/app/oracle/product/fmw/wlserver/server/lib/DemoTrust.jks"), "DemoTrustKeyStorePassPhrase".toCharArray());
        Enumeration aliases = keystore.aliases();
        for(; aliases.hasMoreElements();) {
            String alias = (String) aliases.nextElement();
            Date CertExpiryDate = ((X509Certificate) keystore.getCertificate(alias)).getNotAfter();
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
            //Tue Oct 17 06:02:22 AEST 2006
            Date today = new Date();
            long DateDiff = CertExpiryDate.getTime() - today.getTime();
            long ExpiresIn = DateDiff / (24 * 60 * 60 * 1000);
            System.out.println("Certifiate: " + alias + "\tExpires On: " + CertExpiryDate + "\tFormated Date: " + ft.format(CertExpiryDate)+ "\tToday's Date: " + ft.format(today) + "\tExpires In: "+ ExpiresIn);
        }
    }

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






When you execute the Java program then you might get the Sample Output as below: