Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract raw certificate from PKCS#7 file in JAVA

I would like to achieve the same what this openssl command performs, but programmatically in Java:

openssl pkcs7 -in toBeExported.p7c -inform DER -out certificate.pem -print_certs 

which means that I have a public key certificate (PKCS #7 Certificate) in DER format and I want to extract the raw certificate contained there to a Base64 file. Is there a way to do this?

like image 210
Samsky Avatar asked Oct 18 '25 13:10

Samsky


2 Answers

Something like

FileInputStream is = new FileInputStream( "cert.pkcs7" );
CertificateFactory cf = CertificateFactory.getInstance( "X.509" );
Iterator i = cf.generateCertificates( is ).iterator();
while ( i.hasNext() ) 
{
   Certificate c = (Certificate)i.next();
   // TODO encode c as Base64...
}

should work with PKCS#7 encoded certificates.

Cheers,

like image 87
Anders R. Bystrup Avatar answered Oct 21 '25 04:10

Anders R. Bystrup


Let me add a more complete Java class using modern language features:

/**
 * Reads the certificate chain from a pkcs7 file.
 */
public class Cert {
    public static void main(String[] args) throws Exception {
        try (InputStream inputStream = new FileInputStream("testfile.txt.pkcs7")) {
            final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            certificateFactory.generateCertificates(inputStream).forEach(certificate -> {
                final X509Certificate x509Certificate = (X509Certificate) certificate;
                System.out.printf("subjectDN: %s%n", x509Certificate.getSubjectDN().getName());
            });
        }
    }
}
like image 45
bollin Avatar answered Oct 21 '25 03:10

bollin