Normally a download link is provided where you can download someone else’s certificate. But sometimes a download link isn’t provided or it is easier to export the certificate yourself.

The script mentioned in the ”OpenSSL Command-Line Howto” (http://www.madboa.com/geek/openssl/#cert-retrieve) retrieves only the root certificate but not the complete certificate chain. To solve this problem I extended that script a little bit so that it exports every certificate of the certificate chain in a seperate file. Later on you can import the certificates into the keystore using the keytool command.

Example: Usage of the script

Here you can see how to use this script:

$ ./retrieve-certchain.sh amazon.de
2 certificates found. 

Each certificate must be exported to a different file, 
otherwise the import with keytool won’t work.

Please enter a filename prefix for the certificate files: amazon 
starting export:
amazon1.crt generated.
amazon2.crt generated.

Import the certificates using keytool:

$ $JAVA_HOME/bin/keytool -import -alias amazon1 -file ./amazon1.crt -keystore $JAVA_HOME/jre/lib/security/jssecacerts
$ $JAVA_HOME/bin/keytool -import -alias amazon2 -file ./amazon2.crt -keystore $JAVA_HOME/jre/lib/security/jssecacerts


The retrieve-certchain.sh script

Here is the script that retrieves every certificate of a certificate chain:

#!/bin/sh
#
# usage: retrieve-certchain.sh remote_host_name [port]
#
REMOTEHOST=$1
REMOTEPORT=${2:-443}
TMPFILE=”$(mktemp)”

echo “” | openssl s_client -showcerts -connect ${REMOTEHOST}:${REMOTEPORT} 2>&1 |\
sed -ne ‘/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p’ |\
tr -d ‘\n’ |\
sed -e ’s/-END CERTIFICATE—–/-END CERTIFICATE—–\n/g’ > “${TMPFILE}”

NUM_CERTS=$(wc -l “${TMPFILE}” | awk ‘{print $1}’)

if [ ${NUM_CERTS} -lt 1 ]; then
    echo “No certificates found.”
    exit 0;
fi

echo “${NUM_CERTS} certificates found. ”
echo “”
echo “Each certificate must be exported to a different file, ”
echo “otherwise the import with keytool won\’t work.”
echo “”
echo -n “Please enter a filename prefix for the certificate files: ”
read crtfile

if [ ! -n "$crtfile" ]; then
    echo “no filename given. Exiting”
    exit 0;
fi
echo “starting export:”

while read LINE
do
    let i=$i+1
    filename=${crtfile}${i}.crt
    if [ -f "${filename}" ]; then
        echo “Error: ${filename} exists.”
        echo ”       This script does not override files. Delete them before running this script.”
        continue;
    fi
    # change this line according for automatic keytool import
    echo $LINE | sed -e ’s/-BEGIN CERTIFICATE—–/-BEGIN CERTIFICATE—–\n/’ -e ’s/—–END /\n—–END /’  > “${filename}”
    echo “${filename} generated.”
done < “${TMPFILE}”

rm “${TMPFILE}”