Styles

Monday, August 14, 2023

Importing Trusted Certificate to all your JVM cacerts

Sometimes when you work in a corporate company there are proxies that require certificates to validate Java applications. Usually your company will provide a valid certificate that will validate any requests coming in and going out from your local machine. In order to use your Java applications successfully with your corporation's certificate you need to import it using keytool to the cacerts file for your installed JVM. 

The problem is however you may have multiple JVMs installed and the location may differ from machine to machine. The following bash script locates all the cacerts on your machine and adds the appropriate certificate to them.
#!/usr/bin/env sh
 
PROXY_CERT="${HOME}/Your_Company_Proxy_CA.cer"
KEYSTORE_ALIAS="proxy-root"

echo "Finding cacerts..."
KEYSTORES=$(find / -name cacerts -type f -print 2>/dev/null)
 
while IFS= read -r KEYSTORE
do
  echo "Finding alias ${KEYSTORE_ALIAS} from JDK Keystore ${KEYSTORE}"
  sudo keytool -list -alias ${KEYSTORE_ALIAS} -keystore "${KEYSTORE}" -storepass changeit -v && {
    echo "Deleting alias ${KEYSTORE_ALIAS} from JDK Keystore ${KEYSTORE}"
    sudo keytool -delete -alias ${KEYSTORE_ALIAS} -storepass changeit -noprompt -keystore "${KEYSTORE}"
  } || echo "Adding cert to JDK Keystore ${KEYSTORE}"
  
  sudo keytool -import -trustcacerts -storepass changeit -noprompt -alias ${KEYSTORE_ALIAS} -keystore "${KEYSTORE}" -file "${PROXY_CERT}"
done <<< "${KEYSTORES}"