Dallon Xu
Dallon Xu

Reputation: 80

Validate pkcs7 SignedData by Bouncy Castle in Java

I am working on an implementation of C# SignedCms functionality in Java.

I have a pkcs7 SignedData (see my attachement: https://www.dropbox.com/s/yivani7dvh98wpa/SignedData.bin?dl=0), it can be validated in C#:

    //signed data is loaded from my attached file.
    bool VerifyPKCS7(byte[] signedData)
    {
        try
        {
            SignedCms signedCms = new SignedCms();
            signedCms.Decode(signedData);

            signedCms.CheckSignature(true);

            return true;
        }
        catch
        {

        }

        return false;
    }

But it can't be validated using Bouncy Castle libs(bcprov-jdk15on-153.jar, bcpkix-jdk15on-153.jar) in Java:

  //encapSigData is loaded from my attached file.      
  CMSSignedDataParser     sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), encapSigData);

  sp.getSignedContent().drain();

  Store                   certStore = sp.getCertificates();
  SignerInformationStore  signers = sp.getSignerInfos();

  Collection              c = signers.getSigners();
  Iterator                it = c.iterator();

  while (it.hasNext())
  {
      SignerInformation   signer = (SignerInformation)it.next();
      Collection          certCollection = certStore.getMatches(signer.getSID());

      Iterator        certIt = certCollection.iterator();
      X509CertificateHolder cert = (X509CertificateHolder)certIt.next();

      System.out.println("verify returns: " + signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)));
  }

I got a exception at the first code line(CMSSignedDataParser constructor):

java.lang.ClassCastException: org.bouncycastle.asn1.DERSequenceParser cannot be cast to org.bouncycastle.asn1.ASN1OctetStringParser
at org.bouncycastle.cms.CMSSignedDataParser.<init>(Unknown Source)
at org.bouncycastle.cms.CMSSignedDataParser.<init>(Unknown Source)
at org.bouncycastle.cms.CMSSignedDataParser.<init>(Unknown Source)

After some analyze, I find that the content of contentInfo in SignedData is a Sequence. It seems that bouncycastle can't accept a Sequence to be the content.

How can I get this SignedData to be validated using bouncycastle in Java?

Upvotes: 0

Views: 1756

Answers (1)

David Hook
David Hook

Reputation: 121

The issue here is that unlike a regular CMS message, this is really a PKCS7 one. Support for these has now been added to the bcpkix API in Bouncy Castle.

You can find it in the latest beta at http://www.bouncycastle.org/betas 154b12 or later.

Upvotes: 1

Related Questions