Re: Generate, validate and decode PKCS7 file - SOLVED !

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Re: Generate, validate and decode PKCS7 file - SOLVED !

Nicolas Rossi
I've found the problem/solution. I have to set a flag in CMSSignedDataGenerator.generate() method. The flag name is encapsulate and when it is set to true the signed data will contain the original data.

Now I can decode and verify the pkcs7 file.

This is the final code:

To generate PKCS7 file:

        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        generator.addSigner(keypair.getPrivate(), (X509Certificate) cert, CMSSignedDataGenerator.DIGEST_SHA1);
         ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
        generator.addCertificatesAndCRLs(certs);
        CMSSignedData signedData signedData = generator.generate(new CMSProcessableByteArray(text.getBytes()), true, "BC");
  // <- here is the flag

To decode and verify PKCS7 file:

        CMSSignedData s = new CMSSignedData(sigbytes);
        CertStore certs = s.getCertificatesAndCRLs("Collection", "BC");
        SignerInformationStore signers = s.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        while (it.hasNext())
        {
                X509Certificate cert = null;
                SignerInformation signer = (SignerInformation) it.next();
                Collection certCollection = certs.getCertificates(signer.getSID());
                Iterator certIt = certCollection.iterator();
                cert = (X509Certificate) certIt.next();
                if ( !signer.verify(cert.getPublicKey(), "BC")) throw new Exception("Doesn't verify");
        }
        String content = new String((CMSProcessableByteArray)s.getSignedContent().getContent());


I hope this can be a help for someone.

Nick

--
Ing. Nicolás Rossi
Certant S.A.
Av. de Mayo 666 Piso 3
(C1084AAO) Buenos Aires Argentina
Tel: +54 (11) 5219-0855/6 Int: 112
http://www.certant.com