-1
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,
4

1 回答 1

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
于 2016-05-09T20:05:34.543 回答