Search code examples
javakeystorekeytooljks

Get the Entry type of a KeyStore programatically


With the keytool command, we have this kind of information:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: myname
Creation date: 21-Aug-2011
Entry type: PrivateKeyEntry
Certificate chain length: 1
...

In Java (programatically), how can I retrieve the "Entry type" value to know if it's a private certificate or a public? I'm using the KeyStore Java class this way:

File file = new File(filePath);
String password = password.toCharArray();
KeyStore keyStore = KeyStore.getInstance(format);
keyStore.load(new FileInputStream(file), password);

Solution

  • What you need to do is check if the KeyEntry for the given alias in the KeyStore is a PrivateKeyEntry or a TrustedCertificateEntry.

    char[] password = "mypassword";
    
    ProtectionParameter passwordProtection = new KeyStore.PasswordProtection(password.toCharArray());
    
    KeyEntry entry = keystore.getEntry("myname", passwordProtection);
    
    if (entry instanceof PrivateKeyEntry) {
        // is a private key entry
    }