In this short article I will show you how to create pkcs7 format file to store certificate or chain of certificate.
A pkcs7 format has a file extention of .p7b or .p7c. It can only contains certificates and chain certificates, not the private key.
I will use 3 certificates I have created in previous article and store them in pkcs7 format.
Code:
As an outcome you will have below file in your file system.
Lets open the file and check out the content.
So you can see that it has packaged all the certificates we have provided in the cert chain.
That's it for now...
Stay tuned for my next article related to pkcs8 format....
Please post your comments and doubts!!!
A pkcs7 format has a file extention of .p7b or .p7c. It can only contains certificates and chain certificates, not the private key.
I will use 3 certificates I have created in previous article and store them in pkcs7 format.
Code:
import sun.security.pkcs.ContentInfo;
import sun.security.pkcs.PKCS7;
import sun.security.pkcs.SignerInfo;
import sun.security.x509.AlgorithmId;
import sun.security.x509.X509CertImpl;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class App2 {
public static void main(String[] args) throws IOException, CertificateException {
//loading certificates stored as file
FileInputStream rootCAFile = new FileInputStream("D:\\rootCA.cer");
FileInputStream intermedCAFile = new FileInputStream("D:\\intermedCA.cer");
FileInputStream endUserCertFile = new FileInputStream("D:\\endUserCert.cer");
//create certificate objects from fileinputstream
X509Certificate rootCA = new X509CertImpl(rootCAFile);
X509Certificate intermedCA = new X509CertImpl(intermedCAFile);
X509Certificate endUserCert = new X509CertImpl(endUserCertFile);
//create the certificate hierarchy array
X509Certificate[] chain = new X509Certificate[3];
chain[0] = endUserCert;
chain[1] = intermedCA;
chain[2] = rootCA;
//create pkcs7 object with the cert chain created
PKCS7 pkcs7 = new PKCS7(new AlgorithmId[0], new ContentInfo(ContentInfo.DATA_OID, null),
chain, new SignerInfo[0]);
// store it as .p7b or .p7c format file
FileOutputStream fos = new FileOutputStream("D:\\bundle.p7b");
pkcs7.encodeSignedData(fos);
fos.close();
}
}
As an outcome you will have below file in your file system.
Lets open the file and check out the content.
So you can see that it has packaged all the certificates we have provided in the cert chain.
That's it for now...
Stay tuned for my next article related to pkcs8 format....
Please post your comments and doubts!!!