2015-02-24 30 views
0

在我的春天MVC的Java應用程序,我有一個方法:NoSuchElementException從系統中讀取java應用程序中的p12文件?

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目錄中。

但是,對於我的測試環境中,我將在同一個bin文件夾相同的P12文件在tomcat目錄,並試圖讀取我得到下面的異常文件時:

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]: 

什麼,似乎是想錯了嗎?

回答

0

我反而決定從應用程序中的資源目錄中讀取p12文件,它工作正常。

相關問題