Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking certificates expiration dates in java keystore

Tags:

My java application uses a keystore file in which I have a certificate which is used in ssl connection with active directory server. What I have to do is to check its expiration date and prompt user if its close to expire. I have to do it while my application starts. My idea is to use external program: keytool to display info about certain certificate in the keystore and then do some parsing operations on a string which keytool outputs to find this validation date.

Here's the output of a specific keytool command:

Owner: Issuer: CN=CPD Root CA, DC=cpd, DC=local<br> Serial number: 39e8d1610002000000cb <br>Valid from: Wed Feb 22 21:36:31 CET 2012 until: Thu Feb 21 21:36:31 CET 2013 Certificate fingerprints: <br>          MD5:  82:46:8B:DB:BC:5C:64:21:84:BB:68:E3:4B:D4:35:70<br>          SHA1: 35:52:CA:F2:11:66:1E:50:63:BC:53:A5:50:C1:F0:1E:62:81:BC:3F<br>          Signature algorithm name: SHA1withRSA 

Problem would be with parsing date since I can't be sure in which format it is displayed.

Is there any easier way to check expiration date of certificates included in java keystore file?

like image 347
lou_cypher Avatar asked Mar 01 '12 08:03

lou_cypher


People also ask

How do I view certificate information in a keystore?

You can use the java keytool to list the contents a keystore. In many respects, the java keytool is a competing utility with openssl for keystore, key, and certificate management. The keytool list command will list the contents of your keystore.

Does certificate have expiration date?

According to the CA/Browser forum, an SSL certificate should only be valid for a period of 13 months or 397 days. Ensuring that the certificates are abiding by the latest security standards is also another reason for having a validity period.


2 Answers

Thanks for the direction EJP, here is a block of what I came up with.

    try {         KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());         keystore.load(new FileInputStream("keystoreLocation"), "keystorePassword".toCharArray());         Enumeration<String> aliases = keystore.aliases();         while(aliases.hasMoreElements()){             String alias = aliases.nextElement();             if(keystore.getCertificate(alias).getType().equals("X.509")){                 System.out.println(alias + " expires " + ((X509Certificate) keystore.getCertificate(alias)).getNotAfter());             }         }     } catch (Exception e) {         e.printStackTrace();     } 
like image 150
WillieT Avatar answered Oct 16 '22 20:10

WillieT


Use the java.security.Keystore class to load the keystore and enumerate its contents, and check each certificate for expiry.

like image 23
user207421 Avatar answered Oct 16 '22 21:10

user207421