将PEM转换为PKCS7(Java)

时间:2017-07-24 10:33:32

标签: java certificate pem pkcs#7

我有PEM格式的Byte数组列表(代表链中的每个证书),我想知道是否有办法将它们转换为Java中唯一的PKCS7格式化字符串。

提前谢谢。

1 个答案:

答案 0 :(得分:2)

这是使用基于此answerX509Certificate[]数组构建PKCS#7文件的示例。它不需要私钥

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

}