Search code examples
javakeystorepkcs#12

Java - Why I can't enumerate certificates in a KeyStore by using their alias?


KeyStore keystore_client = KeyStore.getInstance("pkcs12");

try(InputStream keyInput = new FileInputStream("2.pfx")){
  keystore_client.load(keyInput, null);
}
Enumeration<String> e = keystore_client.aliases();
while(e.hasMoreElements()){
  String alias = e.nextElement();
  if(keystore_client.getCertificate(alias)==null)
    throw new RuntimeException("Cannot get Certificate");
}

When I run this code, I always get the exception: "Cannot get Certificate".

How can I extract certificates from a pkcs12 file?

Edit:
The pfx file was created by openssl.

$ openssl pkcs12 -export -out 2.pfx -in server.crt -inkey server.key  
$ keytool  -list -keystore 2.pfx  
Enter keystore password:  

*****************  WARNING WARNING WARNING  *****************  
* The integrity of the information stored in your keystore  *  
* has NOT been verified!  In order to verify its integrity, *  
* you must provide your keystore password.                  *  
*****************  WARNING WARNING WARNING  *****************  

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

1, May 9, 2016, PrivateKeyEntry,

Solution

  • The reason why you are not getting the certificate is because you are not providing a password. Take a closer look at the warning you are getting:

    *****************  WARNING WARNING WARNING  *****************  
    * The integrity of the information stored in your keystore  *  
    * has NOT been verified!  In order to verify its integrity, *  
    * you must provide your keystore password.                  *  
    *****************  WARNING WARNING WARNING  ***************** 
    

    If you do JUnit tests on your code and try keystores with a password and without a password you will see that only the ones that need password will let you get certificates via this code, and of course provided that you input a correct password.

    Another thing you'll see if you try to extract this from the command line is:

    *****************  WARNING WARNING WARNING  *****************
    * The integrity of the information stored in your keystore  *
    * has NOT been verified!  In order to verify its integrity, *
    * you must provide your keystore password.                  *
    *****************  WARNING WARNING WARNING  *****************
    
    keytool error: java.lang.Exception: Alias <1> has no certificate