Skip to content

Instantly share code, notes, and snippets.

@Austinb
Last active February 26, 2020 16:23
Show Gist options
  • Save Austinb/1134768246e8d8f56f1c06f17fbacde2 to your computer and use it in GitHub Desktop.
Save Austinb/1134768246e8d8f56f1c06f17fbacde2 to your computer and use it in GitHub Desktop.
Java keytool replace existing certificate

Fast guide for replacing a certificate in a JAVA key store using keytool and openssl. Useful if you do not want to generate a new csr. This also has commands for extracting the private key in case you lost it or do not have access to it.

This guide is probably incomplete but you have to start somewhere...

First backup your existing keystore file. If you break it you have a copy you can fallback on.

cp /path/to/keystore ~/keystore

All the commands will prompt for passwords. Passwords are usually required when dealing with keytool so it is best to set a password when prompted instead of just entering an empty password.

Extract the private key from your keystore file. You can skip the next two steps if you already have the private key file in PEM format. Change the paths and the alias to match what you need. I recommend using the same alias as the one you are replacing in the keystore.

keytool -importkeystore -srckeystore /path/to/keystore -srcalias your_alias -destalias your_alias -destkeystore /path/to/export.p12 -deststoretype PKCS12

Export the P12 key into PEM format

openssl pkcs12 -in /path/to/export.p12 -nodes -nocerts -out /path/to/export.pem

Convert your crt into a P12 file that we can import into the keystore

openssl pkcs12 -export -in /path/to/cert.crt -inkey /path/to/export.pem -certfile /path/to/bundle.crt -out /path/to/newkeystore.p12 -name your_alias

Note when creating the new P12 file above you will need to make sure the value of -name matches the alias in the keystore you will be importing this P12 file into. If it does not the import will fail with an error like keytool error: java.lang.Exception: Alias <your_hub> does not exist You can verify the alias matches by listing the entries in the P12 file keytool -list -keystore /path/to/newkeystore.p12

Import your P12 into your main keystore file which will prompt you to overwrite your existing alias

keytool -importkeystore -srckeystore /path/to/newkeystore.p12 -srcstoretype PKCS12 -alias your_alias -destkeystore /path/to/keystore

Now you can check your keystore and see that the alias has been updated with the imported P12 file.

keytool -list -keystore /path/to/keystore

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment