05 September 2016

shell script to import certificates into java cacerts

I am not the original author, I just some small enhancements



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#! /bin/bash

if [ $# -eq 0 ]; then
    echo -e "usage: $0 <host>\nexample: $0 abc.com"
    exit -1
fi

KEYTOOL=../../bin/keytool
HOST=$1
PORT=443
KEYSTOREFILE=cacerts
KEYSTOREFILE_BKUP=$KEYSTOREFILE.`date '+%Y%m%d%H%M'`.'original'
KEYSTOREPASS=changeit

if [ ! -f $KEYSTOREFILE ]; then
    echo -e "You must run this script from the directory jdk/jre/lib/security"
    exit -1
fi

#backup the cacerts file
echo -e "\n\n**** BAKCING UP THE $KEYSTOREFILE TO $KEYSTOREFILE_BKUP ****\n\n"
cp $KEYSTOREFILE $KEYSTOREFILE_BKUP


# get the SSL certificate
echo -e "\n\n**** SAVING THE CERTIFCATE TO ${HOST}.cert ****\n\n"
openssl s_client -connect ${HOST}:${PORT} </dev/null \
    | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert

echo -e "\n\n**** USING keytool AT $KEYTOOL ****\n\n"

# create a keystore and import certificate
echo -e "\n\n**** IMPORTING THE CERTIFICATE... ****\n\n"
"$KEYTOOL" -import -noprompt -trustcacerts \
    -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}

echo -e "\n\n**** PRINTING THE CERTIFICATE AFTER IMPORTED ... ****\n\n"
# verify we've got it.
"$KEYTOOL" -list -v -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS} -alias ${HOST} | grep --color=always $HOST
Post a Comment