为KeyStore.TrustedCertificateEntry设置证书?

时间:2014-03-19 01:57:27

标签: java x509certificate keystore

我试图给这只猫上皮:Use PEM Encoded CA Cert on filesystem directly for HTTPS request?另一种方式。

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的网页。

如何将X509Certificate加载到TrustedCertificateEntry

2 个答案:

答案 0 :(得分:3)

我根据Vit Hnilica在loading a certificate from keystore的答案找到了它。由于大多数Stack Overflow答案都以“使用openssl转换”开头,然后使用keytool ......“。

我将会回答这个问题。

在发布答案时,Hat已经去了Vit。 Hnilica的答案是我在浏览Stack Overflow上的类似问题和答案的页面后找到的唯一答案。

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 :(得分:2)

还有另一种方法。

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

TrustedCertificateEntry的ProtectionParameter应为null。