Pergunta

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?

Foi útil?

Solução

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,

Outras dicas

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());
            });
        }
    }
}
public void Read_PKCS7_Cert(String cert_file) throws FileNotFoundException, 
CertificateException
{       
try {

  File file = new File(cert_file);
  FileInputStream fis = new FileInputStream(file);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  Collection c = cf.generateCertificates(fis);
  Iterator i = c.iterator();

  while (i.hasNext()) {
     X509Certificate cert509 = (X509Certificate) i.next();
     System.out.println("IssuerDN: " + cert509.getIssuerDN());
     System.out.println("NotAfter: " + cert509.getNotAfter());
     System.out.println("SerialNumber: " + cert509.getSerialNumber());
     System.out.println("SigAlgName: " + cert509.getSigAlgName());
     System.out.println("IssuerUniqueID: " + 
     Arrays.toString(cert509.getIssuerUniqueID()));
     System.out.println("Signature: " + Arrays.toString(cert509.getSignature()));
      System.out.println("SubjectDN: " + cert509.getSubjectDN());
    }
  }
  catch (FileNotFoundException | CertificateException th) {
      System.out.println(th.toString());
  }
 }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top