Extracting Certificate Expiry Date Using keytool

Last Updated on :March 2, 2024

Java’s keytool utility is a powerful tool for handling cryptographic keys and certificates.  In this blog post, we’ll explore how to extract the expiry date of list certificates using keytool.

To check the expiration date of certificates using the keytool command, you can use the following commands:


keytool -list -v -keystore /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts -storepass USE_PASSWORD  | grep -E '^Alias name:|^Valid from:'

The above command lists the entries in the specified keystore (cacerts) with detailed information about each entry and then filters the output to display only the lines containing “Alias name:” or “Valid from:”.

Here is Output :


Alias name: addtrust_externalca
Valid from: Thu Sep 22 11:22:02 GMT 2011 until: Sun Sep 22 11:22:02 GMT 2030
Alias name: addtrustclass4ca
Valid from: Tue May 30 10:38:31 GMT 2000 until: Sat May 30 10:38:31 GMT 2020
Alias name: aolrootca1
Valid from: Tue May 30 10:44:50 GMT 2000 until: Sat May 30 10:44:50 GMT 2020

Below script is a basic certificate expiration checker for certificates stored in a Java keystore. The script outputs messages indicating whether a certificate has expired, is expiring in less than 10 days, or is still valid.

#!/usr/bin/env bash
#
# AUTHOR: Rakesh Panigrahi
# Command to check the certs in the keystore

KEYSTORE=/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts
KEYSTORE_PW=<PWD>

current_epoch=$(date +%s)
ten_days_in_seconds=$((10 * 24 * 60 * 60))

while read -r ALIAS; do

    ALIAS=$(echo ${ALIAS} | cut -d' ' -f3)

    # read the next line
    read -r UNTIL

    UNTIL=$(echo ${UNTIL} | sed 's/^.*until: //')

    # convert to epoch
    EPOCH=$(date -d "${UNTIL}" +%s)

    # calculate the difference between the expiration date and the current date
    expiration_diff=$((EPOCH - current_epoch))

   # compare with the current time
    if [ $EPOCH -lt $current_epoch ]; then
        echo "${ALIAS} -->  ${UNTIL} has expired."
     else
        # check if the certificate will expire in the next 10 days
        if [ $expiration_diff -le $ten_days_in_seconds ]; then
            echo "${ALIAS} -->  ${UNTIL} is expiring in less than 10 days." 
        else
            echo "${ALIAS} -->  ${UNTIL}"
        fi
    fi
    # do something with it
    # echo "${ALIAS}  -->  ${EPOCH}"
done < <(keytool -list -v -keystore "${KEYSTORE}" -storepass "${KEYSTORE_PW}" | grep -E '^Alias name:|^Valid from:')

You can find the source code for the Bash script discussed in this blog post on GitHub. Feel free to clone or download it for your own use.

https://github.com/rkshpanigrahi/useful-bash-scripts/blob/main/scripts/check-certs.sh

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *