🦍 maniedzi's blog

Mange cacerts with keytool

keytool is used to manage the certificates databases used by the applications written in Java. It allows to store trusted certificates and keys - like the self-signed certificates that normally would not be trusted. The tool is installed along with the [open]JDK package.

Be default, certificate database is stored in $JAVA_HOME/lib/security/cacerts.

Examples

List all certificates in the keystore database:

keytool -list -v -keystore $JAVA_HOME/lib/security/cacerts

Find stored certificate by alias:

keytool -list -v -keystore $JAVA_HOME/lib/security/cacerts -alias mojadomena

Removing certificate by alias:

keytool -delete -alias mojadomena -keystore $JAVA_HOME/lib/security/cacerts

There is a default password for the key store database that need to be provided every time those commands are executed. The password is changeit, and I do not know anyone who is changing it. Add -storepass changeit to the command to prevent asking for password:

keytool -list -storepass changeit \
  -keystore $JAVA_HOME/lib/security/cacerts

Add new certificate to the database:

keytool -importcert \
  -file mycert.crt \
  -storepass changeme \
  -keystore $JAVA_HOME/lib/security/cacerts \
  -alias "mydomain"

Automation

The script below downloads the certificate from the provided server and adds it to the certs database.

#!/bin/bash

PORT=443
SERVER=startpage.com
KEYTOOL=/usr/bin/keytool
STOREFILE=cacerts
PASSWD=changeit

openssl s_client -showcerts -verify 5 \
  -connect $SERVER:443 < /dev/null | \
  awk '/BEGIN CERTIFICATE/,/END CERTIFICATE/{ if(/BEGIN CERTIFICATE/){a++}; out="cert"a".pem"; print >out}'

for cert in *.pem; do
  newname=$(openssl x509 -noout -subject \
    -in $cert | sed -nE 's/.*CN ?= ?(.*)/\1/; s/[ ,.*]/_/g; s/__/_/g; s/_-_/-/; s/^_//g;p' | tr '[:upper:]' '[:lower:]').pem
  mv "${cert}" "${newname}"
  $KEYTOOL -noprompt -importcert -file ${newname} -storepass $PASSWD -keystore $STOREFILE -alias ${newname}
done

There is an RSS feed for this blog.

#work