コード例 #1
0
ファイル: CAdESSignature.cs プロジェクト: 63l06ri5/CAdESLib
        public virtual bool CheckIntegrity(Document detachedDocument)
        {
            try
            {
                bool ret             = false;
                SignerInformation si = null;
                if (detachedDocument != null)
                {
                    // Recreate a SignerInformation with the content using a CMSSignedDataParser

                    CmsSignedDataParser sp = new CmsSignedDataParser(new CmsTypedStream(detachedDocument.OpenStream()), _cmsSignedData.GetEncoded());
                    sp.GetSignedContent().Drain();
                    si = BCStaticHelpers.GetSigner(sp, signerInformation.SignerID);
                }
                else
                {
                    si = signerInformation;
                }
                ret = si.Verify(SigningCertificate);
                return(ret);
            }
            catch (CertificateExpiredException)
            {
                return(false);
            }
            catch (CmsException)
            {
                return(false);
            }
            catch (IOException)
            {
                return(false);
            }
        }
        public static void ReadXmlSigned(this Fattura fattura, Stream stream, bool validateSignature = true)
        {
            CmsSignedData signedFile = new CmsSignedData(stream);

            if (validateSignature)
            {
                IX509Store             certStore   = signedFile.GetCertificates("Collection");
                ICollection            certs       = certStore.GetMatches(new X509CertStoreSelector());
                SignerInformationStore signerStore = signedFile.GetSignerInfos();
                ICollection            signers     = signerStore.GetSigners();

                foreach (object tempCertification in certs)
                {
                    Org.BouncyCastle.X509.X509Certificate certification = tempCertification as Org.BouncyCastle.X509.X509Certificate;

                    foreach (object tempSigner in signers)
                    {
                        SignerInformation signer = tempSigner as SignerInformation;
                        if (!signer.Verify(certification.GetPublicKey()))
                        {
                            throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.SignatureException);
                        }
                    }
                }
            }

            using (var memoryStream = new MemoryStream())
            {
                signedFile.SignedContent.Write(memoryStream);
                fattura.ReadXml(memoryStream);
            }
        }
コード例 #3
0
        public static bool VerifySignatures(FileInfo contentFile, Stream signedDataStream)
        {
            CmsProcessable signedContent = null;
            CmsSignedData  cmsSignedData = null;

            Org.BouncyCastle.X509.Store.IX509Store store = null;
            ICollection signers        = null;
            bool        verifiedStatus = false;

            try
            {
                //Org.BouncyCastle.Security.addProvider(new BouncyCastleProvider());
                signedContent = new CmsProcessableFile(contentFile);
                cmsSignedData = new CmsSignedData(signedContent, signedDataStream);
                store         = cmsSignedData.GetCertificates("Collection");//.getCertificates();
                IX509Store certStore = cmsSignedData.GetCertificates("Collection");
                signers = cmsSignedData.GetSignerInfos().GetSigners();
                foreach (var item in signers)
                {
                    SignerInformation signer   = (SignerInformation)item;
                    var         certCollection = certStore.GetMatches(signer.SignerID);
                    IEnumerator iter           = certCollection.GetEnumerator();
                    iter.MoveNext();
                    var cert = (Org.BouncyCastle.X509.X509Certificate)iter.Current;
                    verifiedStatus = signer.Verify(cert.GetPublicKey());
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(verifiedStatus);
        }
コード例 #4
0
        private void VerifyCounterSignature(SignerInformation signInfo, byte[] certificate)
        {
            SignerInformation csi = GetFirstSignerInfo(signInfo.GetCounterSignatures());

            X509Certificate cert = new X509CertificateParser().ReadCertificate(certificate);

            Assert.IsTrue(csi.Verify(cert));
        }
コード例 #5
0
 public void Validate(X509Certificate cert)
 {
     try
     {
         byte[] b = DigestUtilities.CalculateDigest(certID.GetHashAlgorithmName(), cert.GetEncoded());
         if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), b))
         {
             throw new TspValidationException("certificate hash does not match certID hash.");
         }
         if (certID.IssuerSerial != null)
         {
             if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
             {
                 throw new TspValidationException("certificate serial number does not match certID for signature.");
             }
             GeneralName[] names = certID.IssuerSerial.Issuer.GetNames();
             X509Name      issuerX509Principal = PrincipalUtilities.GetIssuerX509Principal(cert);
             bool          flag = false;
             for (int i = 0; i != names.Length; i++)
             {
                 if (names[i].TagNo == 4 && X509Name.GetInstance(names[i].Name).Equivalent(issuerX509Principal))
                 {
                     flag = true;
                     break;
                 }
             }
             if (!flag)
             {
                 throw new TspValidationException("certificate name does not match certID for signature. ");
             }
         }
         TspUtil.ValidateCertificate(cert);
         cert.CheckValidity(tstInfo.GenTime);
         if (!tsaSignerInfo.Verify(cert))
         {
             throw new TspValidationException("signature not created by certificate.");
         }
     }
     catch (CmsException ex)
     {
         if (ex.InnerException != null)
         {
             throw new TspException(ex.Message, ex.InnerException);
         }
         throw new TspException("CMS exception: " + ex, ex);
     }
     catch (CertificateEncodingException ex2)
     {
         throw new TspException("problem processing certificate: " + ex2, ex2);
     }
     catch (SecurityUtilityException ex3)
     {
         throw new TspException("cannot find algorithm: " + ex3.Message, ex3);
     }
 }
コード例 #6
0
        private void VerifySigner(SignerInformation signer, X509Certificate cert)
        {
            if (cert.GetPublicKey() is DsaPublicKeyParameters)
            {
                DsaPublicKeyParameters key = (DsaPublicKeyParameters)cert.GetPublicKey();

                if (key.Parameters == null)
                {
                    Assert.IsTrue(signer.Verify(GetInheritedKey(key)));
                }
                else
                {
                    Assert.IsTrue(signer.Verify(cert));
                }
            }
            else
            {
                Assert.IsTrue(signer.Verify(cert));
            }
        }
コード例 #7
0
        static void Main(string[] args)
        {
            //if (args.Length > 0)
            //string fullFileName = Path.GetFullPath(args[0]);
            foreach (string fileName in Directory.GetFiles("p7m"))
            {
                FileStream file    = new FileStream(fileName, FileMode.Open);
                bool       isValid = true;
                Console.WriteLine("File to decrypt: " + fileName);
                try
                {
                    CmsSignedData          signedFile  = new CmsSignedData(file);
                    IX509Store             certStore   = signedFile.GetCertificates("Collection");
                    ICollection            certs       = certStore.GetMatches(new X509CertStoreSelector());
                    SignerInformationStore signerStore = signedFile.GetSignerInfos();
                    ICollection            signers     = signerStore.GetSigners();

                    foreach (object tempCertification in certs)
                    {
                        X509Certificate certification = tempCertification as X509Certificate;

                        foreach (object tempSigner in signers)
                        {
                            SignerInformation signer = tempSigner as SignerInformation;
                            if (!signer.Verify(certification.GetPublicKey()))
                            {
                                isValid = false;
                                break;
                            }
                        }
                    }
                    string newFileName = Path.Combine(Directory.CreateDirectory("p7m-extracted").Name, Path.GetFileNameWithoutExtension(fileName));
                    using (var fileStream = new FileStream(newFileName, FileMode.Create, FileAccess.Write))
                    {
                        signedFile.SignedContent.Write(fileStream);
                        Console.WriteLine("File decrypted: " + newFileName);
                    }
                }
                catch (Exception ex)
                {
                    isValid = false;
                }

                Console.WriteLine("File valid: " + isValid);

                ;
            }
            Console.ReadLine();
        }
コード例 #8
0
ファイル: PDF_Validator.cs プロジェクト: page2me/TeDA
        /// <summary>
        /// Validate the signature that valid or not
        /// </summary>
        /// <param name="signedData"></param>
        /// <param name="certificate"></param>
        private void validateSignature(CmsSignedData signedData, X509Certificate2 certificate)
        {
            bool isValid = false;

            SignerInformationStore signers = signedData.GetSignerInfos();
            IEnumerator            it      = signers.GetSigners().GetEnumerator();

            if (it.MoveNext())
            {
                SignerInformation signer = (SignerInformation)it.Current;
                Org.BouncyCastle.X509.X509Certificate cer = DotNetUtilities.FromX509Certificate(certificate);
                isValid = signer.Verify(cer);
            }

            if (!isValid)
            {
                throw new Exception("Signature is not valid");
            }
        }
コード例 #9
0
        public virtual bool CheckIntegrity(Document detachedDocument)
        {
            //TODO jbonilla Verifier?
            //JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder
            //    ();
            try
            {
                bool ret             = false;
                SignerInformation si = null;
                if (detachedDocument != null)
                {
                    // Recreate a SignerInformation with the content using a CMSSignedDataParser
                    CmsSignedDataParser sp = new CmsSignedDataParser(new CmsTypedStream(detachedDocument
                                                                                        .OpenStream()), cmsSignedData.GetEncoded());
                    sp.GetSignedContent().Drain();
                    si = sp.GetSignerInfos().GetFirstSigner(signerInformation.SignerID);
                }
                else
                {
                    si = this.signerInformation;
                }
                //ret = si.Verify(verifier.Build(GetSigningCertificate()));
                ret = si.Verify(GetSigningCertificate());
                return(ret);
            }

            /*catch (OperatorCreationException)
             * {
             *      return false;
             * }*/
            catch (CmsException)
            {
                return(false);
            }
            catch (IOException)
            {
                return(false);
            }
        }
コード例 #10
0
        private static bool VerificaCertificato(EsitoVerifica ev, SignerInformation signer, bool fileOK, Org.BouncyCastle.X509.X509Certificate cert1)
        {
            fileOK = signer.Verify(cert1);

            if (signer.SignedAttributes != null)
            {
                if (signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2] == null)
                {
                    fileOK       = false;
                    ev.status    = EsitoVerificaStatus.ErroreGenerico;
                    ev.message   = "Il formato dell'attributo signingCertificateV2 non è presente";
                    ev.errorCode = "145C";
                }
            }
            else
            {
                fileOK       = false;
                ev.status    = EsitoVerificaStatus.ErroreGenerico;
                ev.message   = "Mancano le signed Attributes obbligatorie( IdAAsigningCertificateV2, MessageDigest, contentType )";
                ev.errorCode = "1450";
            }
            return(fileOK);
        }
        public static void ReadXmlSigned(this Fattura fattura, string filePath)
        {
            CmsSignedData          signedFile  = new CmsSignedData(new FileStream(filePath, FileMode.Open, FileAccess.Read));
            IX509Store             certStore   = signedFile.GetCertificates("Collection");
            ICollection            certs       = certStore.GetMatches(new X509CertStoreSelector());
            SignerInformationStore signerStore = signedFile.GetSignerInfos();
            ICollection            signers     = signerStore.GetSigners();

            foreach (object tempCertification in certs)
            {
                Org.BouncyCastle.X509.X509Certificate certification = tempCertification as Org.BouncyCastle.X509.X509Certificate;

                foreach (object tempSigner in signers)
                {
                    SignerInformation signer = tempSigner as SignerInformation;
                    if (!signer.Verify(certification.GetPublicKey()))
                    {
                        throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.SignatureException);
                    }
                }
            }


            string outFile = Path.GetTempFileName();

            using (var fileStream = new FileStream(outFile, FileMode.Create, FileAccess.Write))
            {
                signedFile.SignedContent.Write(fileStream);
            }

            using (var r = XmlReader.Create(outFile, new XmlReaderSettings {
                IgnoreWhitespace = true, IgnoreComments = true
            }))
            {
                fattura.ReadXml(r);
            }
        }
コード例 #12
0
        /**
         * Validate the time stamp token.
         * <p>
         * To be valid the token must be signed by the passed in certificate and
         * the certificate must be the one referred to by the SigningCertificate
         * attribute included in the the hashed attributes of the token. The
         * certificate must also have the ExtendedKeyUsageExtension with only
         * KeyPurposeID.IdKPTimeStamping and have been valid at the time the
         * timestamp was created.
         * </p>
         * <p>
         * A successful call to validate means all the above are true.
         * </p>
         */
        public void Validate(
            X509Certificate cert)
        {
            IDigest digest;

            try
            {
                digest = DigestUtilities.GetDigest("SHA-1");
            }
            catch (SecurityUtilityException e)
            {
                throw new TspException("cannot find algorithm: " + e.Message, e);
            }

            try
            {
                byte[] certEncoded = cert.GetEncoded();
                digest.BlockUpdate(certEncoded, 0, certEncoded.Length);
                byte[] hash = DigestUtilities.DoFinal(digest);

                if (!Arrays.AreEqual(certID.GetCertHash(), hash))
                {
                    throw new TspValidationException("certificate hash does not match certID hash.");
                }

                if (certID.IssuerSerial != null)
                {
                    if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
                    {
                        throw new TspValidationException("certificate serial number does not match certID for signature.");
                    }

                    GeneralName[] names     = certID.IssuerSerial.Issuer.GetNames();
                    X509Name      principal = PrincipalUtilities.GetIssuerX509Principal(cert);
                    bool          found     = false;

                    for (int i = 0; i != names.Length; i++)
                    {
                        if (names[i].TagNo == 4 &&
                            X509Name.GetInstance(names[i].Name).Equals(principal))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        throw new TspValidationException("certificate name does not match certID for signature. ");
                    }
                }

                TspUtil.ValidateCertificate(cert);

                cert.CheckValidity(tstInfo.GenTime);

                if (!tsaSignerInfo.Verify(cert))
                {
                    throw new TspValidationException("signature not created by certificate.");
                }
            }
            catch (CmsException e)
            {
                if (e.InnerException != null)
                {
                    throw new TspException(e.Message, e.InnerException);
                }

                throw new TspException("CMS exception: " + e, e);
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("problem processing certificate: " + e, e);
            }
        }
コード例 #13
0
ファイル: Rfc4134Test.cs プロジェクト: KimikoMuffin/bc-csharp
		private void VerifySigner(SignerInformation signer, X509Certificate cert)
		{
			if (cert.GetPublicKey() is DsaPublicKeyParameters)
			{
				DsaPublicKeyParameters key = (DsaPublicKeyParameters)cert.GetPublicKey();

				if (key.Parameters == null)
				{
					Assert.IsTrue(signer.Verify(GetInheritedKey(key)));
				}
				else
				{
					Assert.IsTrue(signer.Verify(cert));
				}
			}
			else
			{
				Assert.IsTrue(signer.Verify(cert));
			}
		}
コード例 #14
0
        private DocsPaVO.documento.SignerInfo ExtractSignerInfo(List <string> ErrorMessageLst, IX509Store store, SignerInformation signer)
        {
            DocsPaVO.documento.SignerInfo         thisSinger = new DocsPaVO.documento.SignerInfo();
            Org.BouncyCastle.X509.X509Certificate cert1      = GetCertificate(signer, store);
            try
            {
                if (!signer.Verify(cert1))
                {
                    ErrorMessageLst.Add("Not valid signature");
                }
            }
            catch (Exception e)
            {
                ErrorMessageLst.Add(e.Message);
            }

            thisSinger.isCountersigner = signer.IsCounterSignature;
            if (signer.SignedAttributes != null)
            {
                if (signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2] == null)
                {
                    ErrorMessageLst.Add("Id-AA-SigningCertificateV2 not found");
                }

                if (signer.SignedAttributes[CmsAttributes.MessageDigest] == null)
                {
                    ErrorMessageLst.Add("Pkcs9AtMessageDigest not found");
                }


                if (!signer.IsCounterSignature) //Pare che i controfirmatari non ncessitino di questo parametro
                {
                    if (signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtContentType] == null)
                    {
                        ErrorMessageLst.Add("Pkcs9AtContentType not found");
                    }
                }

                thisSinger.SignatureAlgorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(signer.DigestAlgorithmID.ObjectID);
                if (signer.SignedAttributes[CmsAttributes.SigningTime] != null)
                {
                    Org.BouncyCastle.Asn1.Cms.Attribute sigTime = signer.SignedAttributes[CmsAttributes.SigningTime];
                    if (sigTime.AttrValues.Count > 0)
                    {
                        try
                        {
                            thisSinger.SigningTime = GetSigningTime(sigTime.AttrValues[0]);
                        }
                        catch (Exception e)
                        {
                            ErrorMessageLst.Add("Error retriving SigningTime");
                        }
                    }
                }
            }
            else
            {
                ErrorMessageLst.Add("Missing SignedAttributes");
            }

            if (gestioneTSFirma)
            {
                List <TSInfo> tsArr = new List <TSInfo>();
                if (signer.UnsignedAttributes != null && signer.UnsignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASignatureTimeStampToken] != null)
                {
                    ICollection ret = Org.BouncyCastle.Tsp.TspUtil.GetSignatureTimestamps(signer);
                    foreach (Org.BouncyCastle.Tsp.TimeStampToken token in ret)
                    {
                        VerifyTimeStamp verifyTimeStamp = new VerifyTimeStamp();
                        ICollection     certsColl       = token.GetCertificates("COLLECTION").GetMatches(null);
                        TSInfo          timeStamp       = verifyTimeStamp.getTSCertInfo(certsColl);

                        timeStamp.TSdateTime     = token.TimeStampInfo.GenTime.ToLocalTime();
                        timeStamp.TSserialNumber = token.TimeStampInfo.SerialNumber.ToString();
                        timeStamp.TSimprint      = Convert.ToBase64String(token.TimeStampInfo.TstInfo.MessageImprint.GetEncoded());
                        timeStamp.TSdateTime     = token.TimeStampInfo.GenTime;
                        timeStamp.TSType         = TsType.PKCS;
                        tsArr.Add(timeStamp);
                    }
                }

                if (tsArr.Count > 0)
                {
                    thisSinger.SignatureTimeStampInfo = tsArr.ToArray();
                }
            }
            X509Certificate2 cert = new X509Certificate2(cert1.GetEncoded());

            thisSinger.CertificateInfo.RevocationStatus = CheckCertificate(cert);
            thisSinger.CertificateInfo.X509Certificate  = cert1.GetEncoded();

            thisSinger.CertificateInfo.RevocationStatusDescription = DecodeStatus(thisSinger.CertificateInfo.RevocationStatus);
            ParseCNIPASubjectInfo(ref thisSinger.SubjectInfo, cert.SubjectName.Name);

            thisSinger.CertificateInfo.IssuerName         = cert.IssuerName.Name;
            thisSinger.CertificateInfo.SerialNumber       = cert.SerialNumber;
            thisSinger.CertificateInfo.SignatureAlgorithm = cert.SignatureAlgorithm.FriendlyName;
            thisSinger.CertificateInfo.SubjectName        = cert.SubjectName.Name;
            thisSinger.CertificateInfo.ValidFromDate      = cert.NotBefore;
            thisSinger.CertificateInfo.ValidToDate        = cert.NotAfter;
            thisSinger.CertificateInfo.ThumbPrint         = cert.Thumbprint;

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("CertificateInfo.IssuerName: '{0}'", thisSinger.CertificateInfo.IssuerName);
            sb.AppendFormat("CertificateInfo.SerialNumber: '{0}'", thisSinger.CertificateInfo.SerialNumber);
            sb.AppendFormat("CertificateInfo.SignatureAlgorithm: '{0}'", thisSinger.CertificateInfo.SignatureAlgorithm);
            sb.AppendFormat("CertificateInfo.SubjectName: '{0}'", thisSinger.CertificateInfo.SubjectName);
            sb.AppendFormat("CertificateInfo.ValidFromDate: '{0}'", thisSinger.CertificateInfo.ValidFromDate);
            sb.AppendFormat("CertificateInfo.ValidToDate: '{0}'", thisSinger.CertificateInfo.ValidToDate);
            sb.AppendFormat("CertificateInfo.ThumbPrint: '{0}'", thisSinger.CertificateInfo.ThumbPrint);
            //DocsPaUtils.LogsManagement.Debugger.Write(string.Format("SignedDocument.Verify - {0}", sb.ToString()));


            //gestione controfirma
            if (signer.UnsignedAttributes != null)
            {
                if (signer.UnsignedAttributes[CmsAttributes.CounterSignature] != null)
                {
                    List <DocsPaVO.documento.SignerInfo> cSigsList = new List <DocsPaVO.documento.SignerInfo>();
                    List <string>          csignErrs         = new List <string> ();
                    SignerInformationStore counterSignatures = signer.GetCounterSignatures();
                    foreach (SignerInformation conunterSig in counterSignatures.GetSigners())
                    {
                        DocsPaVO.documento.SignerInfo cSigs = ExtractSignerInfo(csignErrs, store, conunterSig);
                        cSigsList.Add(cSigs);
                    }
                    if (csignErrs.Count > 0)
                    {
                        ErrorMessageLst.AddRange(csignErrs);
                    }
                    if (cSigsList.Count > 0)
                    {
                        thisSinger.counterSignatures = cSigsList.ToArray();
                    }
                }
            }
            return(thisSinger);
        }
コード例 #15
0
        /// <summary>
        ///     Verify signed bytes and PKCS#7 signature.
        /// </summary>
        /// <param name="signedBytes">signed bytes</param>
        /// <param name="signatureBytes">signature bytes</param>
        /// <param name="data">other data</param>
        public void Verify(byte[] signedBytes, byte[] signatureBytes, CryptoSignatureVerificationData data = null)
        {
            if (signedBytes == null)
            {
                throw new ArgumentNullException(nameof(signedBytes));
            }

            if (signatureBytes == null)
            {
                throw new ArgumentNullException(nameof(signatureBytes));
            }

            if (_trustAnchors == null && data?.CertificateBytes == null)
            {
                throw new ArgumentException("No trust anchors given.");
            }

            CmsSignedData signedData;

            try
            {
                CmsProcessableByteArray cmsProcessableByteArray = new CmsProcessableByteArray(signedBytes);
                signedData = new CmsSignedData(cmsProcessableByteArray, signatureBytes);
            }
            catch (Exception e)
            {
                throw new PkiVerificationErrorException("Cannot create signature from " + nameof(signatureBytes), e);
            }

            SignerInformationStore signerInformationStore = signedData.GetSignerInfos();
            ICollection            signerCollection       = signerInformationStore.GetSigners();

            if (signerCollection.Count == 0)
            {
                throw new PkiVerificationFailedException("Signature does not contain any SignerInformation element.");
            }

            IX509Store x509Store = signedData.GetCertificates("collection");

            IEnumerator signerInfoCollectionEnumerator = signerCollection.GetEnumerator();

            while (signerInfoCollectionEnumerator.MoveNext())
            {
                SignerInformation signerInfo = (SignerInformation)signerInfoCollectionEnumerator.Current;

                if (signerInfo == null)
                {
                    throw new PkiVerificationErrorException("Signature does not contain any SignerInformation element.");
                }

                ICollection x509Collection = x509Store.GetMatches(signerInfo.SignerID);
                IEnumerator x509CertificateCollectionEnumerator = x509Collection.GetEnumerator();
                if (!x509CertificateCollectionEnumerator.MoveNext())
                {
                    throw new PkiVerificationErrorException("Signature does not contain any x509 certificates.");
                }

                X509Certificate certificate = (X509Certificate)x509CertificateCollectionEnumerator.Current;

                if (data != null)
                {
                    try
                    {
                        CertificateTimeVerifier.Verify(certificate, data.SignTime);
                    }
                    catch (PkiVerificationFailedCertNotValidException ex)
                    {
                        throw new PkiVerificationFailedCertNotValidException("PKCS#7 signature certificate is not valid.", ex);
                    }
                }

                if (_certificateRdnSelector != null)
                {
                    try
                    {
                        // Verify certificate with rdn selector
                        if (!_certificateRdnSelector.IsMatch(certificate))
                        {
                            throw new PkiVerificationFailedException("Certificate did not match with certificate subject rdn selector.");
                        }
                    }
                    catch (PkiVerificationFailedException)
                    {
                        throw;
                    }
                    catch (Exception e)
                    {
                        throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                    }
                }

                try
                {
                    if (!signerInfo.Verify(certificate))
                    {
                        throw new PkiVerificationFailedException("Signer information does not match with certificate.");
                    }
                }
                catch (CmsException e)
                {
                    throw new PkiVerificationFailedException("Failed to verify PKCS#7 signature.", e);
                }
                catch (Exception e)
                {
                    throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                }

                ISet trustAnchors;

                if (data?.CertificateBytes != null)
                {
                    try
                    {
                        trustAnchors = new HashSet
                        {
                            new TrustAnchor(DotNetUtilities.FromX509Certificate(new X509Certificate2(data.CertificateBytes)), null)
                        };
                    }
                    catch (Exception e)
                    {
                        throw new PkiVerificationErrorException("Cannot create trust anchor certificate from " + nameof(data.CertificateBytes), e);
                    }
                }
                else
                {
                    trustAnchors = _trustAnchors;
                }

                try
                {
                    ValidateCertPath(certificate, x509Store, trustAnchors);
                }
                catch (PkiVerificationFailedException)
                {
                    throw;
                }

                catch (Exception e)
                {
                    throw new PkiVerificationErrorException("Error when verifying PKCS#7 signature.", e);
                }
            }
        }