【问题标题】:Set certificate for KeyStore.TrustedCertificateEntry?为 KeyStore.TrustedCertificateEntry 设置证书?
【发布时间】:2014-04-25 01:01:39
【问题描述】:

我正在尝试给这只猫剥皮: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 中?

【问题讨论】:

    标签: java x509certificate keystore


    【解决方案1】:

    我根据 Vit Hnilica 在loading a certificate from keystore 的回答找到了它。我将把这个问题留给这个答案,因为大多数 Stack Overflow 的答案都以“使用openssl 转换,然后使用keytool ...”开头。

    感谢 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);
    

    【讨论】:

      【解决方案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 应该为空。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-18
        • 2015-06-21
        • 2013-09-24
        • 1970-01-01
        • 1970-01-01
        • 2017-06-08
        • 2016-01-04
        相关资源
        最近更新 更多