sorin
sorin

Reputation: 170808

How to import and trust a webserver certificate in java using keytool in a single command?

Use case: you have a webserver that is using a self-signed certificate or a certificate emitted by an untrusted CA and you just want to be sure that your Java server will communicate properly with this server.

I found several tutorials on the net but none was using an automated/scriptable approach.

Upvotes: 1

Views: 2169

Answers (1)

sorin
sorin

Reputation: 170808

Also published as https://gist.github.com/3164098 (patches are welcome)


#!/bin/bash
REMHOST=$1
REMPORT=${2:-443}

KEYSTORE_PASS=changeit
KEYTOOL=/opt/jira/jre/bin/keytool

# FYI: the default keystore is located in ~/.keystore

if [ -z "$REMHOST" ]
    then
    echo "ERROR: Please specify the server name to import the certificatin from, eventually followed by the port number, if other than 443."
    exit 1
    fi

set -e

rm -f $REMHOST.pem

echo -n | openssl s_client -connect $REMHOST:$REMPORT 2>/dev/null  $REMHOST.pem

if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST >/dev/null
    then
    echo "Key of $REMHOST already found, skipping it."
    else
    $KEYTOOL -import -trustcacerts -noprompt -storepass ${KEYSTORE_PASS} -alias $REMHOST -file $REMHOST.pem
    fi

Upvotes: 3

Related Questions