2012-04-30 102 views
2

我使用下面的代碼在輸入證書之前檢查CA的證書?

FileInputStream fileInputStream = new FileInputStream("c:/server.jks"); 
    keyStore.load(fileInputStream, "keystore".toCharArray()); 
    fileInputStream.close(); 
    keyStore.setCertificateEntry(alias, new X509Certificate(trustedCertificate)); 

    FileOutputStream fileOutputStream = new FileOutputStream("c:/server.jks"); 
    keyStore.store(fileOutputStream, "keystore".toCharArray()); 
    fileOutputStream.close(); 

現在我看到該證書被輸入到我的信任,但該客戶簽署證書的CA的證書沒有出現在我的信任將客戶端證書到我servertruststore。因此,我想知道在將證書輸入密鑰庫之前,我們是否可以檢查CA證書是否可用?

+0

可能重複[驗證Java中的證書拋出一個異常 - 無法找到有效的證書路徑請求的目標(http://stackoverflow.com/questions/10411433/驗證-A-證書在-java的拋出-AN-異常無法找到的,有效-CERT) – Bruno

回答

3

我想你要做的是驗證證書是否已經由root權限頒發,或者是否已經自簽名。我認爲你使用的是cacerts的默認java密鑰庫。 我沒有測試的代碼,但我認爲這可能是你的問題的解決方案:

  1. 從以下鏈接取出並修改代碼:

How can I get a list of trusted root certificates in Java?

 String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar); 
     Set<X509Certificate> additionalCerts = new HashSet<X509Certificate>(); 
     FileInputStream is = new FileInputStream(filename); 
     KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); 
     String password = "changeit"; 
     keystore.load(is, password.toCharArray()); 

     // This class retrieves the most-trusted CAs from the keystore 
     PKIXParameters params = new PKIXParameters(keystore); 

     // Get the set of trust anchors, which contain the most-trusted CA certificates 
     Iterator it = params.getTrustAnchors().iterator(); 
     while(it.hasNext()) { 
      TrustAnchor ta = (TrustAnchor)it.next(); 
      // Get certificate 
      X509Certificate cert = ta.getTrustedCert(); 
      additionalCerts.add(cert); 
     } 
  1. 然後,您可以使用以下代碼將客戶端證書和包含所有根CA的集合傳遞給verifyCertificate(X509Certificate cert,Set additionalCerts)方法下面的代碼:的

http://www.nakov.com/blog/2009/12/01/x509-certificate-validation-in-java-build-and-verify-chain-and-verify-clr-with-bouncy-castle/