amportugal
amportugal

Reputation: 124

Convert PEM to PKCS7 (Java)

I have a List of Byte arrays (representing each certificate from a chain), in PEM format, and I would like to know if there's a way to convert these to a unique PKCS7 formatted String, in Java.

Thank you in advance.

Upvotes: 1

Views: 1916

Answers (1)

pedrofb
pedrofb

Reputation: 39291

This is an example to build a PKCS#7 file using a X509Certificate[] array based on this answer. It does not require the private key

//Export a certificate list to PKCS#7
public static byte[] exportCertificatesAsPkcs7(X509Certificate certs[]) throws Exception {

    List certList = new ArrayList();
    for (X509Certificate certificate: certs){
        certList.add(new X509CertificateHolder(certificate.getEncoded()));
    }
    Store certStore = new JcaCertStore(certList);

    CMSProcessableByteArray msg = new CMSProcessableByteArray("Hello World".getBytes());
    CMSSignedDataGenerator    gen = new CMSSignedDataGenerator(); 
    gen.addCertificates(certStore);
    CMSSignedData data = gen.generate(msg, "BC"); 
    return data.getEncoded();

}

Upvotes: 2

Related Questions