Skip to content
Snippets Groups Projects

Create Java Keystore - Private key NOT encrypted

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Simão Miguel Anjo Martins
    createJavaKeystore-ClearKey.sh 1.27 KiB
    #!/bin/sh
    
    SERVER_NAME=$1
    CERTIFICATE="${SERVER_NAME}.pem"
    KEY="${SERVER_NAME}.key"
    
    if [[ ! -f $CERTIFICATE && ! -f $KEY ]]; then
    	echo "Could not find \"$CERTIFICATE\" and \"$KEY\". Exiting."
    	exit 1
    fi
    
    function askForPassword() {
    	unset PASSWORD PASSWORD_2
    	while true; do
    		read -p "Enter password for $1: " -s PASSWORD
    		echo
    		read -p "Re-enter password for $1: " -s PASSWORD_2
    		echo
    		if [ "$PASSWORD" = "$PASSWORD_2" ]; then
    			break
    		else
    			echo "Passwords did not match. Please try again."
    		fi
    	done
    }
    
    P12_KEYSTORE=${SERVER_NAME}.p12
    echo "1) Create a PKCS12 keystore from $CERTIFICATE and ${KEY}."
    echo "We need to create a PKCS12 keystore because keytool is not able to generate a Java keystore from a X.509 certificate and its key."
    askForPassword $P12_KEYSTORE
    KEYSTORE_PASSWORD=$PASSWORD
    openssl pkcs12 -export -in $CERTIFICATE \
    -inkey $KEY -out $P12_KEYSTORE \
    -name $SERVER_NAME -passout pass:$KEYSTORE_PASSWORD
    echo "Created file $P12_KEYSTORE"
    echo ""
    
    
    JAVA_KEYSTORE=${SERVER_NAME}.keystore.jks
    echo "2) Import $P12_KEYSTORE into a new Java keystore"
    keytool -importkeystore -srckeystore $P12_KEYSTORE -srcstoretype PKCS12 \
    -srcstorepass $KEYSTORE_PASSWORD -alias $SERVER_NAME -deststorepass $KEYSTORE_PASSWORD \
    -destkeystore $JAVA_KEYSTORE
    echo "Created file $JAVA_KEYSTORE"
    0% or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment