Search code examples
ssl-certificatekeystorekeytoolandroid-keystore

How to remove all certificates from cacerts?


I know I may use

keytool -delete -alias alias -keystore .keystore

to remove some certificates from certificate storages. But I've got 109 certificates stored in cacerts: keytool -list result

How to remove them with one command? Or, in other words, how do you clear cacerts storage?


Solution

  • There is no one command from keytool to delete all the entries in a keystore. You have to do a few workarounds to achieve this.

    You can do it either by writing a simple Java code using the KeyStore api:

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(new File("KEYSTORE_PATH")), "changeit".toCharArray());
    
    Enumeration<String> aliases = ks.aliases();
    
    while (aliases.hasMoreElements())
    {
        String alias = aliases.nextElement();
    
        ks.deleteEntry(alias);
    }
    
    ks.store(new FileOutputStream(new File("KEYSTORE_PATH")), "changeit".toCharArray());
    

    (Or)

    Create a similar store, since you already know the type of cacerts keystore (minor workaround here).

    1. Create a KeyStore with a keypair initially when creating the cacerts keystore file.

    keytool -genkeypair -keystore cacerts -storepass changeit

    1. Delete the initially create key pair entry.

    keytool -delete -keystore cacerts -storepass changeit -alias mykey

    Since the cacerts is the default keystore, you don't specify the other attributes in the keytool command, let java handle the default values for you. Now you should have an empty cacerts keystore.