Search code examples
javakeystorejks

Rename JKS alias with java programmatically


I would like to know how can I rename an alias of a keystore, programmatically in java, not using keytool.

I have my java.security.KeyStore object, containing an certain alias. How can I rename it?


Solution

  • The KeyStore API does not provide a rename operation for aliases. But what you can do is:

    1. Save the content (key pair, certificates) of the keystore entry that you want to rename.
    2. Delete the entry.
    3. Create a new entry with the saved content and the new alias.

    As Java code:

    Key privateKey = keyStore.getKey(alias, password.toCharArray());
    Certificate[] certs = keyStore.getCertificateChain(alias);
    keyStore.setKeyEntry(newAlias, privateKey, password.toCharArray(), certs);
    keyStore.deleteEntry(alias);
    

    Of course this does not work if the private key is stored on a hardware device (smartcard or HSM) and therefore is not readable.

    If the keystore entry contains a trusted certificate, the code looks a bit different:

    Certificate cert = keyStore.getCertificate(alias);
    keyStore.setCertificateEntry(newAlias, cert);
    keyStore.deleteEntry(alias);