Search code examples
javasecuritysslkeystorejks

How to convert java KeyStore to PKCS7 .p7b file?


Convert X509 to PKCS7

Create PKCS7 from keystore

I have tried both the answers above but I feel these do not suit my need since Based on the below link I can summarize that PKCS7 is used for two purposes,

  1. Creating signatures, digest etc CMS(Crytographic message syntax)
  2. A container for certificates

Based on this I summarized

My need is more of point no.2. I just want to create a .p7b file using all the certificates that I have in a KeyStore object. Since PKCS7 cannot contain private key. The above two answers generate a signature and what not. Am I missing something? is that the way to go ahead or is there another way?

I can extract certs from a .p7b file using

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();
   System.out.println(Base64.getEncoder.encodeToString(c.getEncoded());
}

I am asking how to do the reverse, i.e create a .p7b file from Certificate[] or Java KeyStore

Okay I found the solution:

Solution In this we can create what I exactly asked for but I still get the signed data which is generated. I don't want that. A simple .p7b package which I already have has no signerInfo will the .p7b created by this solution have it?

Is this the right way to do it?


Solution

  • Found the solution in this link:

    code:

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

    Useful links related to PKCS7:

    Convert X509 to PKCS7

    Create PKCS7 from keystore