Search code examples
javasecuritykeystore

Identifying entries in java keystore


In my program I need to get key from keypair included in a pkcs12 archive using java. As I don't know keypair alias, I have to iterate through all aliases in keystore. Question is, how can I identify keypair? I'm using this code to get a key and certificate chain:

KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(new File(p12Path)), p12Password);
Enumeration aliases = ks.aliases();
String alias = (String) aliases.nextElement();
p12Key = ks.getKey(alias, p12Password);
p12Chain = ks.getCertificateChain(alias);

I would like to identify entry as keypair or just certificate/chain

Entry entry = kspkcs12.getEntry(alias, null);

Solution

  • Call KeyStore.isKeyEntry

    Note the only possible Entry's are a PrivateKeyEntry containing a privatekey and (matching) chain of one or more cert(s), or a TrustedCertEntry containing exactly one cert but never more than one. PKCS12 format doesn't support SecretKeyEntry.

    In practice PKCS12 files created by anything other than Java will usually have only one PrivateKeyEntry and nothing else, but there is no guarantee.