2013-08-22 138 views
3

我們正在使用小程序進行加密解密。我們發現一些數字證書的意外問題。一個系統具有證書,我們無法從該證書找到私鑰,但通過再次安裝相同的證書可以正常工作。找不到證書中的私鑰

Java Plug-in 10.25.2.17 
Using JRE version 1.7.0_25-b17 Java HotSpot(TM) 64-Bit Server VM 
User home directory = C:\Users\admin 

要訪問私鑰,我們使用下面的代碼。

private PrivateKey getPrivateKeyFromKeyStore(String pubkey, KeyStore browser) { 
     PrivateKey privateKey = null; 
     String pubKey1 = ""; 
     if (browser != null) { 
      try { 
       Field spiField = KeyStore.class.getDeclaredField("keyStoreSpi"); 
       spiField.setAccessible(true); 
       KeyStoreSpi spi = (KeyStoreSpi) spiField.get(browser); 
       Field entriesField = spi.getClass().getSuperclass().getDeclaredField("entries"); 
       entriesField.setAccessible(true); 
       @SuppressWarnings("rawtypes") 
       Collection entries = (Collection) entriesField.get(spi); 
       for (Object entry : entries) { 
        String alias = (String) invokeGetter(entry, "getAlias"); 
        X509Certificate[] certificateChain = (X509Certificate[]) invokeGetter(entry, "getCertificateChain"); 
        for (X509Certificate current : certificateChain) { 
         pubKey1 = this.bASE64Encoder.encode(current.getPublicKey().getEncoded()); 
         if (pubkey.equals(pubKey1) && !pubkey.equals("")) { 
          privateKey = (PrivateKey) invokeGetter(entry, "getPrivateKey"); 
          return privateKey; 
         } 
        } 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
       return null; 
      } 
     } 
     return privateKey; 
    } 
+0

你不需要所有這些反射來調用KeyStore API。嘗試使用已發佈的內容。 – EJP

+0

無法得到它..你會plz解釋一點點細節。像哪行代碼我必須改變... –

+2

更改它們*全部。*扔掉它,看看Javadoc。KeyStore中已經有公開的方法來枚舉內容並找出每個元素的類型。 – EJP

回答

0

你不會找到證書的私鑰,因爲它必須在你的密鑰庫,當然,如果你擁有CSR :)

有一個小竅門產生你的證書,請問是例如證書過期了嗎?

無論如何,問題是不太清楚:(如果您有證書,你必須具有用於簽署您的應用程序的密鑰存儲......這將是更好的你提供更多的細節......