How to Load Pkcs7 (. P7B) File in Java

I have a pkcs7 file, and I want to load it and extract its contents.

I tried these two methods:

byte[] bytes = Files.readAllBytes(Paths.get("myfile.p7b"));
FileInputStream fi = new FileInputStream(file);

//Creating PKCS7 object
PKCS7 pkcs7Signature = new PKCS7(bytes);

or this

FileInputStream fis = new FileInputStream(new File("myfile.p7b"));
PKCS7 pkcs7Signature = new PKCS7(fis);

but I got IOException: Sequence tag error

So how can I load this .p7b file ?

3

1 Answer

Finally I did it with BouncyCastle library.

PKCS#7 is a complex format, also called CMS. Sun JCE has no direct support to PKCS#7.

This is the code that I used to extract my content:

// Loading the file first
   File f = new File("myFile.p7b");
   byte[] buffer = new byte[(int) f.length()];
   DataInputStream in = new DataInputStream(new FileInputStream(f));
   in.readFully(buffer);
   in.close();

   //Corresponding class of signed_data is CMSSignedData
   CMSSignedData signature = new CMSSignedData(buffer);
   Store cs = signature.getCertificates();
   SignerInformationStore signers = signature.getSignerInfos();
   Collection c = signers.getSigners();
   Iterator it = c.iterator();

   //the following array will contain the content of xml document
   byte[] data = null;

   while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = cs.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

        CMSProcessable sc = signature.getSignedContent();
        data = (byte[]) sc.getContent();
    }

If you want to verify the signature of this PKCS7 file against X509 certificate, you must add the following code to the while loop:

// ************************************************************* //
// ********************* Verify signature ********************** //
//get CA public key
// Create a X509 certificat
CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");

// Open the certificate file
FileInputStream fileinputstream = new FileInputStream("myCA.cert");

//get CA public key
PublicKey pk = certificatefactory.generateCertificate(fileinputstream).getPublicKey();

X509Certificate myCA = new JcaX509CertificateConverter().setProvider("BC").getCertificate(cert);

myCA.verify(pk);
System.out.println("Verfication done successfully ");
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest