Skip to content

Instantly share code, notes, and snippets.

@L-Briand
Created March 28, 2024 08:13
Show Gist options
  • Save L-Briand/3b0578585c3e2646cfa2afa2968a1b9e to your computer and use it in GitHub Desktop.
Save L-Briand/3b0578585c3e2646cfa2afa2968a1b9e to your computer and use it in GitHub Desktop.
#!/usr/bin/env sh
usage() {
echo "usage:"
echo " $0 -k <key.pk8> -c <cert.x509.pem> [-o <keystore.jks>] [-s <keystore_password>]"
if [ -n "$1" ] ; then
echo "FILE: \"$1\" NOT FOUND"
fi
exit 1
}
while getopts ":k:c:" option; do
case "${option}" in
k)
KEY=${OPTARG}
if [ -z "$KEY" ] ; then usage ; fi;
if [ ! -f "$KEY" ] ; then usage $KEY ; fi;
;;
c)
CERT=${OPTARG}
if [ -z "$CERT" ] ; then usage ; fi;
if [ ! -f "$CERT" ] ; then usage $CERT ; fi;
;;
o)
OUT=${OPTARG}
;;
a)
KEYSTORE_ALIAS=${OPTARG}
;;
s)
KEYSTORE_PASSWORD=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
if [ -z "$OUT" ] ; then OUT="output.jks"; fi
if [ -z "$KEYSTORE_PASSWORD" ] ; then KEYSTORE_PASSWORD="a_password"; fi
if [ -z "$TEMP_PRIV_DER" ] ; then TEMP_PRIV_DER="private_temp.pem"; fi
if [ -z "$TEMP_PRIV_PKCS12" ] ; then TEMP_PRIV_PKCS12="private_temp.pk12"; fi
if [ -z "${KEY}" ] || [ -z "${CERT}" ] ; then
usage
fi
if [ -f "$OUT" ] ; then
echo "Deleting $OUT"
rm "$OUT"
fi
echo "==="
echo "Export private key to pem file"
openssl pkcs8 -in "$KEY" -inform DER -outform PEM -out "$TEMP_PRIV_DER" -nocrypt
echo "==="
echo "Creating pkcs12 file from private key and certificate"
openssl pkcs12 -export -in "$CERT" -inkey "$TEMP_PRIV_DER" \
-password pass:"${KEYSTORE_PASSWORD}" \
-out "$TEMP_PRIV_PKCS12"
echo "==="
echo "Creating keystore from pkcs12 file"
keytool -importkeystore \
-srcstoretype PKCS12 \
-srckeystore "$TEMP_PRIV_PKCS12" \
-srcstorepass "$KEYSTORE_PASSWORD" \
-deststorepass "$KEYSTORE_PASSWORD" \
-destkeystore "$OUT"
rm "$TEMP_PRIV_DER" "$TEMP_PRIV_PKCS12"
echo "==="
echo "Keystore generated to $OUT"
echo "Keystore alias is '1'"
echo "Keystore password is '$KEYSTORE_PASSWORD'"
echo "==="
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment