2014-03-19 61 views
0

我想這個皮膚貓:Use PEM Encoded CA Cert on filesystem directly for HTTPS request?另一種方式。爲KeyStore.TrustedCertificateEntry設置證書?

Java有一個類KeyStore.TrustedCertificateEntry,但我無法弄清楚如何將證書加載到其中。我的代碼類似於以下:

import java.security.KeyStore.TrustedCertificateEntry; 
... 

X509Certificate ca = (X509Certificate) CertificateFactory(...); 
KeyStore ks = TrustedCertificateEntry(ca); 

和:

X509Certificate ca = (X509Certificate) CertificateFactory(...); 
KeyStore ks = KeyStore.TrustedCertificateEntry(ca); 

和:

X509Certificate ca = (X509Certificate) CertificateFactory(...); 
KeyStore ks = new KeyStore.TrustedCertificateEntry(ca); 

和:

X509Certificate ca = (X509Certificate) CertificateFactory(...); 
KeyStore ks = new KeyStore.TrustedCertificateEntry(ca); 

該計劃將失敗,並錯誤編譯:

SuperCert.java:33: error: cannot find symbol 
KeyStore ks = TrustedCertificateEntry(ca); 
       ^
    symbol: method TrustedCertificateEntry(X509Certificate) 
    location: class TestCert 

加載我的X509證書到KeyStore後,我計劃在TrustManagerFactory使用它,並最終抓取網頁與HttpsURLConnection

如何裝載一個X509CertificateTrustedCertificateEntry

回答

3

,我發現它的基礎上維生素Hnilica的在loading a certificate from keystore答案。我將離開這個問題的答案,因爲大多數堆棧溢出答案開始與「openssl轉換,然後使用keytool ...」。

帽子的關閉發佈該答案。維尼卡的答案是唯一的答案我通過對堆棧溢出類似的問題和答案的網頁涉水後發現的。

String CA_FILE = ...; 

FileInputStream fis = new FileInputStream(CA_FILE); 
X509Certificate ca = (X509Certificate) CertificateFactory.getInstance(
     "X.509").generateCertificate(new BufferedInputStream(fis)); 

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); 
ks.load(null, null); 
ks.setCertificateEntry(Integer.toString(1), ca); 

TrustManagerFactory tmf = TrustManagerFactory 
     .getInstance(TrustManagerFactory.getDefaultAlgorithm()); 
tmf.init(ks); 
1

也有另一種方法。

CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 
X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(file)); 
keyStore.setEntry(alias, new KeyStore.TrustedCertificateEntry(certificate), null); 

ProtectionParameter爲TrustedCertificateEntry爲空。