I'm trying to skin this cat: Use PEM Encoded CA Cert on filesystem directly for HTTPS request? another way.

Java has a class KeyStore.TrustedCertificateEntry, but I can't figure out how to load a certificate into it. My code looks similar to below:

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

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

And:

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

And:

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

And:

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

The program fails to compile with errors similar to:

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

After loading my X509 cert into the KeyStore, I plan on using it in a TrustManagerFactory and ultimately fetching a web page with HttpsURLConnection.

How does one load a X509Certificate into a TrustedCertificateEntry?

有帮助吗?

解决方案

I found it based on Vit Hnilica's answer at loading a certificate from keystore. I"m going to leave the question with this answer since most Stack Overflow answers start with "convert with openssl, then use keytool ...".

Hat's off to Vit for posting that answer. Hnilica's answer is the only one I found after wading through pages of similar questions and answers on 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);

其他提示

There is also another approach.

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

ProtectionParameter for TrustedCertificateEntry should be null.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top