Java - 为什么我不能使用别名在 KeyStore 中枚举证书?

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");
}

当我运行这段代码时,我总是得到异常:"Cannot get Certificate".

如何从 pkcs12 文件中提取证书?

编辑:
pfx 文件是由 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,

您没有获得证书的原因是您没有提供密码。仔细查看您收到的警告:

*****************  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  ***************** 

如果您对代码进行 JUnit 测试并尝试使用密码和不使用密码的密钥库,您会发现只有需要密码的密钥库才能让您通过此代码获得证书,当然前提是您输入了正确的密码。

如果您尝试从命令行提取它,您会看到的另一件事是:

*****************  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