Convert PEM to PKCS7 (Java)

2019-08-19 03:14发布

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.

1条回答
beautiful°
2楼-- · 2019-08-19 03:44

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();

}
查看更多
登录 后发表回答