4

I have a PKCS#7 signature that have the content‐type signed data and it embeds an XML document, and I have to extract the xml document from this PKCS7 file.

Anyone know how to do that in java ??

1
  • This doesn't work for me, can you please post your complete file along with sample p7 file so that I can map it to how I am doing it.
    – Vaibs
    Commented May 23, 2017 at 16:15

1 Answer 1

3

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 ");
1
  • can U share a code to sign a file with pkcs7? Commented May 28, 2018 at 18:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .