How to convert a long date to short date from SSL certificates | Unix KSH

Viewed 9426

I'm wondering if is possible to convert a date as show Oct 31 00:00:00 2013 GMT to 10-31-2013.

I'm getting the date as follow:

NotBeforeDate=$(openssl x509 -noout -in ${CERTIFICATE} -dates | grep "notBefore")

The date that I'm getting is Oct 31 00:00:00 2013 GMT and I wanted to convert it to 10-31-2013.

There's any command that could do that? Or do I have to do it all manually?

If so, the best way is create my own function and send the long date as parameter and return a short date.

4 Answers

This script works for me when checking a url with certificate.

date --date="$(echo | openssl s_client -servername $DOMAIN -connect $DOMAIN:$PORT | openssl x509 -noout -enddate | awk -F '=' '{print $NF}' )" --iso-8601

PORT is 443 by default.

Not to duplicate the explanations for the date command in previous answers, here's a compact Bash function that reads a certificate file and outputs either the start or end date in either ISO format or as a Unix timestamp (useful for integer comparison), and can be used on Linux or macOS:

# cert_date <date_type> <out_format> <cert_file> [openssl_opts...]
#  date_type: start|end
# out_format: iso|unix
cert_date() {
  local type=$1 out=$2 args date opts fmt
  [ "$type" == start ] && args=(-startdate) || args=(-enddate)
  date=$(openssl x509 "${args[@]}" -noout -in "${@:3}")
  [[ "$OSTYPE" == darwin* ]] && opts=(-juf "%b %d %T %Y %Z") || opts=(-ud)
  [ "$out" == unix ] && fmt="%s" || fmt="%Y-%m-%dT%TZ"
  date "${opts[@]}" "${date/*=/}" +"$fmt"
}

Of course, you can enhance by changing fmt to suit your output format needs, and even add a case statement to accept more formats.

Examples:

cert_date start iso  ${CERTIFICATE}
cert_date end   unix ${CERTIFICATE} -inform der

I made a bash OneLiner from the ideas above. Maybe it is useful for somebody:

(Use 'cut -c 10-' when greeping notAfter)

date -d "`openssl x509 -dates -noout -in /path/to/cert.pem | grep notBefore | cut -c 11-`" +%Y.%m.%d
Related