Java - 为什么我不能通过使用别名来枚举KeyStore中的证书?

时间:2016-05-09 07:48:46

标签: java keystore pkcs12

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

当我运行此代码时,我总是得到例外:&#34;无法获得证书&#34;

如何从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,

1 个答案:

答案 0 :(得分:1)

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

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