Friday, May 6, 2016

Update Java Key Store with Renewed Client Certificate and Existing Private Key

Convention:
Bold: positive confirmation that the command executed correctly
Italic: do not be alarmed, this may appear to be an error, however it is not
input_prompt: the appropriate information must be entered

Export the old private key from the keystore.
command:
keytool -importkeystore -srckeystore privatekeystore.jks -storepass KeystoreStorePassword -destkeystore old-private.p12 -deststoretype PKCS12 -deststorepass KeystoreStorePassword
output:
(if you have other public certs in the keystore you will be prompted for each)
Problem importing entry for alias trusted.cert.com: java.security.KeyStoreException: TrustedCertEntry not supported.
Entry for alias trusted.cert.com not imported.
Do you want to quit the import process? [no]:  no
Import command completed:  1 entries successfully imported, 1 entries failed or cancelled

Extract the raw RSA key from the old private p12.
command:
openssl pkcs12 -in old-private.p12 -clcerts -nodes -nocerts | openssl rsa > private.key
output:
Enter Import Password: KeystoreStorePassword
MAC verified OK
writing RSA key

Merge the raw RSA key with the renewed certificate to generate the new private key.
command:
openssl pkcs12 -export -des -out new-private.p12 -inkey private.key -in renewed.pem
output:
Enter Export Password: KeystoreStorePassword
Verifying - Enter Export Password: KeystoreStorePassword
unable to write 'random state'

Remove the old private key from the keystore.
command:
keytool -delete -alias private.cert.com -keystore privatekeystore.jks -storepass KeystoreStorePassword
output: (none)

Import the new private key into into the keystore.
command:
keytool -v -importkeystore -srckeystore new-store.p12 -srcstoretype PKCS12 -storepass KeystoreStorePassword -destkeystore privatekeystore.jks -deststoretype JKS -deststorepass KeystoreStorePassword
output:
Entry for alias 1 successfully imported.
Import command completed:  1 entries successfully imported, 0 entries failed or cancelled
[Storing privatekeystore.jks]

Change the alias associated with the private certificate within the keystore.
command:
keytool -changealias -keystore privatekeystore.jks -alias 1 -destalias private.cert.com -storepass KeystoreStorePassword
output: (none)

Validate by listing the certificates in the keystore.
command:
keytool -list -keystore privatekeystore.jks -storepass KeystoreStorePassword
output:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 2 entries

trusted.cert.com, April 08, 2018, trustedCertEntry,
Certificate fingerprint (MD5): 35:F2:23:68:46:96:A6:38:AA:B2:09:4D:21:F6:9A:47
private.cert.com, May 4, 2016, PrivateKeyEntry,
Certificate fingerprint (MD5): 75:B8:80:C6:99:B7:FC:2B:E4:40:E6:4C:A6:46:66:B9:F3:B2:FA:E2