简体   繁体   中英

Extract multiple X.509 certificates from PEM-formatted file in Java

I have a method which extracts a X.509 certificate from a given PEM-formatted file, using the bouncycastle library.

Imports:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.openssl.PEMParser;

Method:

/**
 * Reads an X509 certificate from a PEM file.
 *
 * @param certificateFile The PEM file.
 * @return the X509 certificate, or null.
 * @throws IOException if reading the file fails
 * @throws CertificateException if parsing the certificate fails
 */
public static X509Certificate readCertificatePEMFile(File certificateFile) throws IOException, CertificateException {
    if (certificateFile.exists() && certificateFile.canRead()) {
        try (InputStream inStream = new FileInputStream(certificateFile)) {
            try (PEMParser pemParser = new PEMParser(new InputStreamReader(inStream))) {
                Object object = pemParser.readObject();
                if (object != null && object instanceof X509CertificateHolder) {
                    return new JcaX509CertificateConverter().getCertificate( (X509CertificateHolder)object );
                }
            }
        }
    }
    return null;
}

This works well for "normal" certificate files, eg a server certificate. If I have a CA chain certificate file, containing multiple certificates, how could I achieve extracting all certificates from this file (the method shown only extracts the first certificate in the file).

Try this code, it handles multiple certificates and Private key entry im PEM file

Security.addProvider(new BouncyCastleProvider());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
while((object = pemParser.readObject())!=null)
{
    if(object instanceof X509CertificateHolder)
    {
        X509Certificate x509Cert = (X509Certificate) new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object);
    }
    else if(object instanceof PEMEncryptedKeyPair)
    {
        if(password==null) throw new IllegalArgumentException("Password required for parsing RSA Private key");

        PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
        converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    }
    else if(object instanceof PEMKeyPair)
    {
        converter.getKeyPair((PEMKeyPair) object);
    }     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM