我正在研究Java中C#SignedCms功能的实现。

我有一个pkcs7 SignedData(请参阅我的附件:https://www.dropbox.com/s/yivani7dvh98wpa/SignedData.bin?dl=0),可以在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;
    }


但是无法使用Java中的Bouncy Castle库(bcprov-jdk15on-153.jar,bcpkix-jdk15on-153.jar)进行验证:

  //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)));
  }


我在第一行代码(CMSSignedDataParser构造函数)中遇到了异常:

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)


经过一些分析,我发现SignedData中contentInfo的内容是一个Sequence。看来Bouncycastle无法接受Sequence作为内容。

如何在Java中使用Bouncycastle验证此SignedData?

最佳答案

这里的问题是,与常规CMS消息不同,这实际上是PKCS7消息。现在,对这些支持已添加到Bouncy Castle中的bcpkix API中。

您可以在http://www.bouncycastle.org/betas 154b12或更高版本的最新Beta中找到它。

09-03 21:58