从系统读取 java 应用程序中的 p12 文件时出现 NoSuchElementException?

NoSuchElementException when reading p12 file in java application from system?

在我的 spring MVC java 应用程序中,我有一个方法:

public static PrivateKey getPrivateKey( String password, InputStream privateKeyFileStream) {
    KeyStore ks;
    Key key = null;
    try {
      ks = KeyStore.getInstance("PKCS12");
      ks.load(privateKeyFileStream, password.toCharArray());

      Enumeration<String> enumeration = ks.aliases();

      // uses the default alias
      String keyAlias = (String) enumeration.nextElement();

      key = ks.getKey(keyAlias, password.toCharArray());
    } catch (KeyStoreException e) {
      ErrorLog.Log(ErrorLog.FATAL, "Error creating WebService. Failed to read private key", e, "WebService", "constructor");
    } catch (NoSuchAlgorithmException e) {
      ErrorLog.Log(ErrorLog.FATAL, "Error creating WebService. Failed to read private key", e, "WebService", "constructor");
    } catch (CertificateException e) {
      ErrorLog.Log(ErrorLog.FATAL, "Error creating WebService. Failed to read private key", e, "WebService", "constructor");
    } catch (IOException e) {
      ErrorLog.Log(ErrorLog.FATAL, "Error creating WebService. Failed to read private key", e, "WebService", "constructor");
    } catch (UnrecoverableKeyException e) {
      ErrorLog.Log(ErrorLog.FATAL, "Error creating WebService. Failed to read private key", e, "WebService", "constructor");
    }

    return (PrivateKey) key;
  }

当我在本地应用程序中使用此方法时,如下所示:

File file = new File("../bin/file.p12");
InputStream privateKeyFileStream = null;
try {
  privateKeyFileStream = FileUtils.openInputStream(file);
} catch (IOException e) {
  ErrorLog.Log(ErrorLog.FATAL, "Error creating WebService.", e, "WebService", "constructor");
}
PrivateKey privateKey = getPrivateKey("password", privateKeyFileStream);

一切正常。 p12 文件位于我的 tomcat 文件夹的 bin 目录中。

但是,对于我的测试环境,我将相同的 p12 文件放在 tomcat 目录中的相同 bin 文件夹中,并且在尝试读取该文件时出现以下异常:

java.util.NoSuchElementException
    at java.util.Collections$EmptyEnumeration.nextElement(Collections.java:3083)
    at com.class.util.class.Class.getPrivateKey(ClassUtils.java:92)
    at com.class.util.class.Class.getInstance(Class.java:77)
    at

引发错误的代码行是:

String keyAlias = (String) enumeration.nextElement();

它基本上无法在 p12 文件中找到任何证书条目,但是当我 运行

keytool -list -keystore file.p12 -storepass password -storetype PKCS12 -v

在我的本地系统和测试环境位置,它显示:

Your keystore contains 1 entry

Alias name: test
Creation date: Feb 11, 2015
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:

好像出了什么问题?

我决定从应用程序的资源目录中读取 p12 文件,效果很好。