Bash: calculating number of days till certificate expiration using openssl

The openssl utility can be used to show the details of a certificate, including its ‘Not After’ expiration date in string format.  This can be transformed into “how many days till expiration” with a bit of Bash date math.

Create test certificate and key

Using a line provided by Diego Woitasen for non-interactive self-signed certification creation, let’s create a 90 day certificate.

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 90 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"

Show ‘Not After’ certificate date string

Using openssl, we can show the expiration date of that certificate in string format.

$ openssl x509 -in cert.pem -text -noout | grep 'Not After :'
Not After : Sep 7 10:13:57 2024 GMT

Calculate the number of days till expiration

Using a custom datediff function provided by camh, this date string can be turned into an integer representing how many days until expiration of the certificate.

function datediff() {
    d1=$(date -d "$1" +%s)
    d2=$(date -d "$2" +%s)
    echo $(( (d1 - d2) / 86400 + 1 ))
}

cert_expiration_str=$(openssl x509 -in cert.pem -text -noout | grep -Po "Not After : \K.*" | head -n1)
echo "days till expiration:" $(datediff "$cert_expiration_str" "$(date -u)")

I have the full openssl_cert_days_till_expiration.sh posted on github.

REFERENCES

openssl man page

unixexchange, user ‘camh’ provides datediff function

stackoverflow, diego woitasen provides non-interactive creation of self-signed cert

NOTES

As contributed by Christian Kugler, another method of checking expiration is the openssl ‘checkend’ flag

# will cert expire in 5 days?
$ openssl s_client -connect fabianlee.org:443 </dev/null 2> /dev/null|openssl x509 -noout -checkend $((86400*5)); echo $?
Certificate will not expire