convert CertStore into X509Certificate[ ] array JA

2019-08-05 04:39发布

问题:

I made a cert store and want to add another certificate from another function in this class.

Make chain in class 1 with caCert and intermediateCert:

List<X509Certificate> certList = new ArrayList<X509Certificate>();
certList.add(0, interCert);
certList.add(1, caCert);
Store<X509Certificate> certs = new JcaCertStore(certList);
certStore = new JcaCertStoreBuilder().addCertificates(certs).build();

I want to add a new build user certificate in class 2:

certStore = new JcaCertStoreBuilder().addCertificate(certHolder).build();

To save the new key to my KeyStore I need an array of the certificates (X509Certificate[]). How can I convert the certStore file to an array to get the privatekeyentry working?

PrivateKeyEntry privKeyEntry = new PrivateKeyEntry(pair.getPrivate(), chain);
store.setEntry(alias, privKeyEntry, new KeyStore.PasswordProtection(storePassword));

回答1:

I'm using BouncyCastle 1.56 and JDK 1.7.

I think the easiest way is to get all the certificates from the cert store and add them to an array (instead of creating another cert store and converting).

To get all the certificates in the cert store, you can do:

// get all certificates in certStore
Collection<? extends Certificate> allCerts = certStore.getCertificates(null);

Some implementations don't accept the null argument. In this case, you must create a selector like this (using java.security.cert.X509CertSelector class):

Collection<? extends Certificate> allCerts = certStore.getCertificates(new X509CertSelector() {
    @Override
    public boolean match(Certificate cert) {
        // match all certificates (so it'll return all of them)
        return true;
    }
});

After that, allCerts will have the 2 certificates that are in certStore.

Now you create your array and add all the certificates you need:

// create array
X509Certificate[] certificatesArray = new X509Certificate[3];

// add certificates in allCerts (the 2 that were in certStore)
int i = 0;
for (Certificate c : allCerts) {
    certificatesArray[i] = (X509Certificate) c;
    i++;
}

// add the new certificate (newCert being a X509Certificate)
certificatesArray[2] = newCert;

Note: If your new certificate's type is a org.bouncycastle.cert.X509CertificateHolder, you can convert it to a java.security.cert.X509Certificate using the org.bouncycastle.cert.jcajce.JcaX509CertificateConverter class:

X509CertificateHolder certHolder = ...;
X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);

Or you can do it manually with a java.security.cert.CertificateFactory:

X509CertificateHolder certHolder = ...;
CertificateFactory f = CertificateFactory.getInstance("X509");
X509Certificate cert = (X509Certificate) f.generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()));