Extract raw certificate from PKCS#7 file in JAVA

Tags: , , , ,



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?

Answer

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,



Source: stackoverflow