예제 #1
0
        private SignerInformation GetFirstSignerInfo(SignerInformationStore store)
        {
            IEnumerator e = store.GetSigners().GetEnumerator();

            e.MoveNext();
            return((SignerInformation)e.Current);
        }
예제 #2
0
        public static bool ValidateSignature(byte[] messageBytes, byte[] signatureBytes, X509Certificate certificate)
        {
            CmsProcessable         signedContent    = new CmsProcessableByteArray(messageBytes);
            CmsSignedData          signedData       = new CmsSignedData(signedContent, signatureBytes);
            IX509Store             certificateStore = signedData.GetCertificates("Collection");
            SignerInformationStore signerInfoStore  = signedData.GetSignerInfos();
            ICollection            signers          = signerInfoStore.GetSigners();

            foreach (SignerInformation signer in signers)
            {
                bool isChainValid = ValidateCertificateChain(certificateStore, signer.SignerID);
                if (!isChainValid)
                {
                    return(false);
                }

                bool verified = signer.Verify(certificate);
                if (!verified)
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #3
0
        /// <param name="signedData"></param>
        /// <returns></returns>
        public virtual CmsSignedData ExtendCMSSignedData(CmsSignedData signedData, Document
                                                         originalData, SignatureParameters parameters)
        {
            SignerInformationStore   signerStore = signedData.GetSignerInfos();
            List <SignerInformation> siArray     = new List <SignerInformation>();
            //Iterator<SignerInformation> infos = signerStore.GetSigners().Iterator();
            IEnumerator infos = signerStore.GetSigners().GetEnumerator();

            while (infos.MoveNext())
            {
                SignerInformation si = (SignerInformation)infos.Current;
                try
                {
                    siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData));
                }
                catch (IOException)
                {
                    //LOG.Error("Exception when extending signature");
                    siArray.Add(si);
                }
            }
            SignerInformationStore newSignerStore = new SignerInformationStore(siArray);

            return(CmsSignedData.ReplaceSigners(signedData, newSignerStore));
        }
예제 #4
0
    public static CmsSignedData ReplaceSigners(CmsSignedData signedData, SignerInformationStore signerInformationStore)
    {
        CmsSignedData cmsSignedData = new CmsSignedData(signedData);

        cmsSignedData.signerInfoStore = signerInformationStore;
        Asn1EncodableVector asn1EncodableVector  = new Asn1EncodableVector();
        Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();

        foreach (SignerInformation signer in signerInformationStore.GetSigners())
        {
            asn1EncodableVector.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
            asn1EncodableVector2.Add(signer.ToSignerInfo());
        }
        Asn1Set      asn1Set      = new DerSet(asn1EncodableVector);
        Asn1Set      asn1Set2     = new DerSet(asn1EncodableVector2);
        Asn1Sequence asn1Sequence = (Asn1Sequence)signedData.signedData.ToAsn1Object();

        asn1EncodableVector2 = new Asn1EncodableVector(asn1Sequence[0], asn1Set);
        for (int i = 2; i != asn1Sequence.Count - 1; i++)
        {
            asn1EncodableVector2.Add(asn1Sequence[i]);
        }
        asn1EncodableVector2.Add(asn1Set2);
        cmsSignedData.signedData  = SignedData.GetInstance(new BerSequence(asn1EncodableVector2));
        cmsSignedData.contentInfo = new ContentInfo(cmsSignedData.contentInfo.ContentType, cmsSignedData.signedData);
        return(cmsSignedData);
    }
예제 #5
0
        private void VerifySignatures(CmsSignedData s, byte[] contentDigest)
        {
            IX509Store             x509Certs = s.GetCertificates("Collection");
            IX509Store             x509Crls  = s.GetCrls("Collection");
            SignerInformationStore signers   = s.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();

                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate)certEnum.Current;

                VerifySigner(signer, cert);

                if (contentDigest != null)
                {
                    Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
                }
            }

            ICollection certColl = x509Certs.GetMatches(null);
            ICollection crlColl  = x509Crls.GetMatches(null);

            Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count);
            Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count);
        }
        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);
            }
        }
예제 #7
0
 public void AddSigners(SignerInformationStore signerStore)
 {
     foreach (SignerInformation signer in signerStore.GetSigners())
     {
         _signers.Add(signer);
         AddSignerCallback(signer);
     }
 }
        private static SignerInformation GetFirstSignerInfo(SignerInformationStore store)
        {
            var signers    = store.GetSigners();
            var enumerator = signers.GetEnumerator();

            enumerator.MoveNext();

            return((SignerInformation)enumerator.Current);
        }
예제 #9
0
파일: MainForm.cs 프로젝트: random9/SignPDF
        //  Sign the message with the private key of the signer.
        static public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached, bool UsaTSA, string TSAurl, string TSAuser, string TSApass)
        {
            try
            {
                SHA256Managed        hashSha256 = new SHA256Managed();
                byte[]               certHash   = hashSha256.ComputeHash(signerCert.RawData);
                EssCertIDv2          essCert1   = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);
                SigningCertificateV2 scv2       = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });
                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2));
                Asn1EncodableVector v = new Asn1EncodableVector();
                v.Add(CertHAttribute);
                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);
                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();
                var rsa = (RSACryptoServiceProvider)signerCert.PrivateKey;
                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(signerCert);
                cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);
                ArrayList certList = new ArrayList();
                certList.Add(certCopy);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                CmsProcessableByteArray file    = new CmsProcessableByteArray(msg); //CmsProcessableFile(File);
                CmsSignedData           Firmato = cms.Generate(file, false);        //se settato a true, il secondo argomento integra l'intero file

                byte[] bb = Firmato.GetEncoded();

                if (UsaTSA)
                {
                    CmsSignedData          sd      = new CmsSignedData(bb);
                    SignerInformationStore signers = sd.GetSignerInfos();
                    byte[]            signature    = null;
                    SignerInformation signer       = null;
                    foreach (SignerInformation signer_ in signers.GetSigners())
                    {
                        signer = signer_;
                        break;
                    }

                    signature = signer.GetSignature();
                    Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass));
                    signer = SignerInformation.ReplaceUnsignedAttributes(signer, at);
                    IList signerInfos = new ArrayList();
                    signerInfos.Add(signer);
                    sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos));
                    bb = sd.GetEncoded();
                }
                return(bb);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(null);
            }
        }
    public static SignerInformation AddCounterSigners(SignerInformation signerInformation, SignerInformationStore counterSigners)
    {
        Org.BouncyCastle.Asn1.Cms.SignerInfo     signerInfo         = signerInformation.info;
        Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInformation.UnsignedAttributes;
        Asn1EncodableVector asn1EncodableVector  = (unsignedAttributes == null) ? new Asn1EncodableVector() : unsignedAttributes.ToAsn1EncodableVector();
        Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();

        foreach (SignerInformation signer in counterSigners.GetSigners())
        {
            asn1EncodableVector2.Add(signer.ToSignerInfo());
        }
        asn1EncodableVector.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.CounterSignature, new DerSet(asn1EncodableVector2)));
        return(new SignerInformation(new Org.BouncyCastle.Asn1.Cms.SignerInfo(signerInfo.SignerID, signerInfo.DigestAlgorithm, signerInfo.AuthenticatedAttributes, signerInfo.DigestEncryptionAlgorithm, signerInfo.EncryptedDigest, new DerSet(asn1EncodableVector)), signerInformation.contentType, signerInformation.content, null));
    }
예제 #11
0
        public static SignerInformation GetSignerInfoByEnumeration(SignerInformationStore signerInformationStore, SignerID id)
        {
            SignerInformation si = null;

            foreach (SignerInformation s in signerInformationStore.GetSigners())
            {
                if (s.SignerID == id)
                {
                    si = s;
                    break;
                }
            }
            return(si);
        }
예제 #12
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();
        }
예제 #13
0
        /// <summary>
        /// Método que busca en las demás firmas el tipo de contenido firmado
        /// </summary>
        /// <param name="siStore"></param>
        /// <returns></returns>
        private BcCms.Attribute GetContentHintAttribute(SignerInformationStore siStore)
        {
            var signers = siStore.GetSigners();

            foreach (SignerInformation signerInfo in signers)
            {
                BcCms.Attribute contentHint = signerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAAContentHint];

                if (contentHint != null)
                {
                    return(contentHint);
                }
            }

            return(null);
        }
예제 #14
0
        private SignerInformation ExtractSignerInfo(CmsSignedDataParser parser)
        {
            //Extract the signer info
            SignerInformationStore signerInfoStore = parser.GetSignerInfos();

            if (signerInfoStore.Count != 1)
            {
#if NETFRAMEWORK
                trace.TraceEvent(TraceEventType.Error, 0, "The message to complete does not contain a single signature");
#else
                logger.LogError("The message to complete does not contain a single signature");
#endif
                throw new InvalidMessageException("The message does not contain a single signature");
            }

            return(signerInfoStore.GetSigners().Cast <SignerInformation>().First());
        }
예제 #15
0
        /// <summary>
        /// Método que busca en las demás firmas el message-digest que coincida con el algoritmo de huella dado
        /// </summary>
        /// <param name="siStore"></param>
        /// <param name="digestMethod"></param>
        /// <returns></returns>
        private byte[] GetDigestValue(SignerInformationStore siStore, DigestMethod digestMethod)
        {
            var signers = siStore.GetSigners();

            foreach (SignerInformation signerInfo in signers)
            {
                if (signerInfo.DigestAlgOid == digestMethod.Oid)
                {
                    BcCms.Attribute digest  = signerInfo.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest];
                    DerOctetString  derHash = (DerOctetString)digest.AttrValues[0];

                    return(derHash.GetOctets());
                }
            }

            return(null);
        }
        public void TestAttributeGenerators()
        {
            IList        certList = new ArrayList();
            MemoryStream bOut     = new MemoryStream();

            certList.Add(OrigCert);
            certList.Add(SignCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            CmsAttributeTableGenerator signedGen   = new SignedGenAttributeTableGenerator();
            CmsAttributeTableGenerator unsignedGen = new UnsignedGenAttributeTableGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert,
                          CmsSignedDataStreamGenerator.DigestSha1, signedGen, unsignedGen);

            gen.AddCertificates(x509Certs);

            Stream sigOut = gen.Open(bOut, true);

            byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
            sigOut.Write(testBytes, 0, testBytes.Length);

            sigOut.Close();

            CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());

            sp.GetSignedContent().Drain();

            VerifySignatures(sp);

            //
            // check attributes
            //
            SignerInformationStore signers = sp.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                checkAttribute(signer.GetContentDigest(), signer.SignedAttributes[dummyOid1]);
                checkAttribute(signer.GetSignature(), signer.UnsignedAttributes[dummyOid2]);
            }
        }
예제 #17
0
        /// <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");
            }
        }
        // taken from bouncy castle SignedDataTest.cs
        private static bool VerifySignatures(
            CmsSignedData sp)
        {
            var                    signaturesValid = true;
            IX509Store             x509Certs       = sp.GetCertificates("Collection");
            SignerInformationStore signers         = sp.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();
                certEnum.MoveNext();
                Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)certEnum.Current;

                signaturesValid &= signer.Verify(cert);
            }
            return(signaturesValid);
        }
예제 #19
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Document ExtendSignatures(Document document, Document originalData
                                                 , SignatureParameters parameters)
        {
            try
            {
                CmsSignedData            signedData  = new CmsSignedData(document.OpenStream());
                SignerInformationStore   signerStore = signedData.GetSignerInfos();
                List <SignerInformation> siArray     = new List <SignerInformation>();

                foreach (SignerInformation si in signerStore.GetSigners())
                {
                    try
                    {
                        //jbonilla - Hack para evitar errores cuando una firma ya ha sido extendida.
                        //Se asume que sólo se extiende las firmas desde BES.
                        //TODO jbonilla - Se debería validar hasta qué punto se extendió (BES, T, C, X, XL).
                        if (si.UnsignedAttributes.Count == 0)
                        {
                            siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData));
                        }
                        else
                        {
                            //LOG.Error("Already extended?");
                            siArray.Add(si);
                        }
                    }
                    catch (IOException)
                    {
                        //LOG.Error("Exception when extending signature");
                        siArray.Add(si);
                    }
                }

                SignerInformationStore newSignerStore = new SignerInformationStore(siArray);
                CmsSignedData          extended       = CmsSignedData.ReplaceSigners(signedData, newSignerStore);
                return(new InMemoryDocument(extended.GetEncoded()));
            }
            catch (CmsException)
            {
                throw new IOException("Cannot parse CMS data");
            }
        }
예제 #20
0
        public static byte[] getHashFromSignature(byte[] signature)
        {
            CmsSignedData content = new CmsSignedData(signature);

            byte[] retval = null;
            try
            {
                SignerInformationStore sistore = content.GetSignerInfos();
                foreach (SignerInformation signer in sistore.GetSigners())
                {
                    if (signer.SignedAttributes != null)
                    {
                        if (signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtMessageDigest] != null)
                        {
                            Asn1Encodable enc = signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtMessageDigest].AttrValues[0];
                            retval = Org.BouncyCastle.Asn1.Asn1OctetString.GetInstance(enc).GetOctets();
                        }
                    }
                    else
                    {
                        IX509Store  store     = content.GetCertificates("Collection");
                        ICollection certsColl = store.GetMatches(null);
                        foreach (Org.BouncyCastle.X509.X509Certificate cert in certsColl)
                        {
                            signer.Verify(cert);
                            retval = signer.GetContentDigest();
                            break;
                        }
                    }
                    if (retval != null)
                    {
                        return(retval);
                    }
                }
            }
            catch
            {
                return(getSha256(extractSignedContent(signature)));
            }

            return(null);
        }
        public void TestSignHashWithBouncyCastle()
        {
            byte[] hashBytes = System.Convert.FromBase64String(Base64encodedHashToSign);

            byte[] signedCmsData = SignatureProvider.SignatureProvider.Sign(hashBytes, SignerName, SignerEmail, SignerCountry, SignerOrganization);

            CmsSignedData          cmsSignedData = new CmsSignedData(signedCmsData);
            IX509Store             x509Certs     = cmsSignedData.GetCertificates("Collection");
            SignerInformationStore signers       = cmsSignedData.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                Assert.AreEqual(1, certCollection.Count);

                IEnumerator certEnum = certCollection.GetEnumerator();
                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate)certEnum.Current;

                Assert.AreEqual(cert.SubjectDN.ToString(), "CN=Cyril Thirion,E=cyril.thirion\\[email protected],C=FR,O=Acme");

                Assert.AreEqual(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtContentType].AttrValues[0].ToString(), PkcsObjectIdentifiers.Data.ToString());
                Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest]);
                Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2]);
                Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime]);

                Assert.AreEqual(
                    "#" + BitConverter.ToString(hashBytes).Replace("-", ""),
                    signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest].AttrValues[0].ToString(), true
                    );

                byte[] signedData = signer.GetEncodedSignedAttributes();
                System.IO.File.WriteAllBytes("/tmp/tmp.txt", signedData);
                ISigner s = SignerUtilities.GetSigner("SHA256withRSA");
                s.Init(false, cert.GetPublicKey());
                s.BlockUpdate(signedData, 0, signedData.Length);
                Assert.IsTrue(s.VerifySignature(signer.GetSignature()), "Signature verification failed.");
            }
        }
예제 #22
0
        /// <summary>
        /// The method used to verify signature.
        /// </summary>
        /// <param name="sp"></param>
        /// <returns></returns>
        public static bool VerifySignatures(CmsSignedDataParser sp)
        {
            List <bool>            result      = new List <bool>();
            IX509Store             x509Certs   = sp.GetCertificates("Collection");
            SignerInformationStore signerInfos = sp.GetSignerInfos();
            var signers = signerInfos.GetSigners();

            foreach (SignerInformation signer in signers)
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);
                foreach (Org.BouncyCastle.X509.X509Certificate cert in certCollection)
                {
                    var isValid = signer.Verify(cert);
                    if (!isValid)
                    {
                        throw new Exception("Certificate verification error, the signer could not be verified.");
                    }
                    result.Add(isValid);
                }
            }
            return(result.TrueForAll(m => m == true));
        }
예제 #23
0
        private void VerifySignatures(CmsSignedDataParser sp)
        {
            CmsTypedStream sc = sp.GetSignedContent();

            if (sc != null)
            {
                sc.Drain();
            }

            IX509Store             x509Certs = sp.GetCertificates("Collection");
            SignerInformationStore signers   = sp.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();
                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate)certEnum.Current;

                VerifySigner(signer, cert);
            }
        }
        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);
            }
        }
예제 #25
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Document ExtendSignature(object signatureId, Document document, Document
                                                originalData, SignatureParameters parameters)
        {
            SignerID toExtendId = (SignerID)signatureId;

            try
            {
                CmsSignedData            signedData  = new CmsSignedData(document.OpenStream());
                SignerInformationStore   signerStore = signedData.GetSignerInfos();
                List <SignerInformation> siArray     = new List <SignerInformation>();
                //Iterator<object> infos = signerStore.GetSigners().Iterator();
                IEnumerator infos = signerStore.GetSigners().GetEnumerator();
                while (infos.MoveNext())
                {
                    SignerInformation si = (SignerInformation)infos.Current;
                    if (si.SignerID.Equals(toExtendId))
                    {
                        try
                        {
                            siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData));
                        }
                        catch (IOException)
                        {
                            //LOG.Error("Exception when extending signature");
                            siArray.Add(si);
                        }
                    }
                }
                SignerInformationStore newSignerStore = new SignerInformationStore(siArray);
                CmsSignedData          extended       = CmsSignedData.ReplaceSigners(signedData, newSignerStore);
                return(new InMemoryDocument(extended.GetEncoded()));
            }
            catch (CmsException)
            {
                throw new IOException("Cannot parse CMS data");
            }
        }
        private void VerifySignatures(
            CmsSignedDataParser sp,
            byte[]                          contentDigest)
        {
            IX509Store             certStore = sp.GetCertificates("Collection");
            SignerInformationStore signers   = sp.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = certStore.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();

                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate)certEnum.Current;

                Assert.IsTrue(signer.Verify(cert));

                if (contentDigest != null)
                {
                    Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
                }
            }
        }
예제 #27
0
		private SignerInformation GetFirstSignerInfo(SignerInformationStore store)
		{
			IEnumerator e = store.GetSigners().GetEnumerator();
			e.MoveNext();
			return (SignerInformation)e.Current;
		}
예제 #28
0
        static void PKCS7()
        {
            GostCryptoConfig.ProviderType = ProviderTypes.VipNet;
            Config.InitCommon();

            BCX509.X509Certificate bcCert = null;
            using (var g = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm())
            {
                bool   detached = false;
                byte[] data     = File.ReadAllBytes("test.xml");

                var certBytes = g.ContainerCertificateRaw;

                BCX509.X509CertificateParser _x509CertificateParser = new BCX509.X509CertificateParser();
                bcCert = _x509CertificateParser.ReadCertificate(certBytes);

                ICollection <BCX509.X509Certificate> certPath = new List <BCX509.X509Certificate>();
                certPath.Add(bcCert);

                IDigest digest  = new Gost3411Digest();
                string  hashOid = GostCryptoConfig.DefaultHashOid;

                byte[] dataHash = ComputeDigest(digest, data);

                // Construct SignerInfo.signedAttrs
                Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector();

                // Add PKCS#9 contentType signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.3"),
                        new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1"))));

                // Add PKCS#9 messageDigest signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.4"),
                        new DerSet(new DerOctetString(dataHash))));

                // Add PKCS#9 signingTime signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.5"),
                        new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow)))));

                DerSet signedAttributes = new DerSet(signedAttributesVector);
                byte[] pkcs1Digest      = ComputeDigest(digest, signedAttributes.GetDerEncoded());
                byte[] pkcs1DigestInfo  = CreateDigestInfo(pkcs1Digest, hashOid);

                // hash


                //var signature = g.CreateSignature(hash);
                var formatter = new GostSignatureFormatter(g);
                var signature = formatter.CreateSignature(pkcs1Digest);

                // Construct SignerInfo
                SignerInfo signerInfo = new SignerInfo(
                    new SignerIdentifier(new IssuerAndSerialNumber(bcCert.IssuerDN, bcCert.SerialNumber)),
                    new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null),
                    signedAttributes,
                    new AlgorithmIdentifier(new DerObjectIdentifier(GostCryptoConfig.DefaultSignOid), null),
                    new DerOctetString(signature),
                    null);

                // Construct SignedData.digestAlgorithms
                Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();
                digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null));

                // Construct SignedData.encapContentInfo
                ContentInfo encapContentInfo = new ContentInfo(
                    new DerObjectIdentifier("1.2.840.113549.1.7.1"),
                    (detached) ? null : new DerOctetString(data));

                // Construct SignedData.certificates
                Asn1EncodableVector certificatesVector = new Asn1EncodableVector();
                foreach (BCX509.X509Certificate cert in certPath)
                {
                    certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
                }

                // Construct SignedData.signerInfos
                Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();
                signerInfosVector.Add(signerInfo.ToAsn1Object());

                // Construct SignedData
                SignedData signedData = new SignedData(
                    new DerSet(digestAlgorithmsVector),
                    encapContentInfo,
                    new BerSet(certificatesVector),
                    null,
                    new DerSet(signerInfosVector));

                // Construct top level ContentInfo
                ContentInfo contentInfo = new ContentInfo(
                    new DerObjectIdentifier("1.2.840.113549.1.7.2"),
                    signedData);

                var res = contentInfo.GetDerEncoded();
                File.WriteAllBytes("test.p7", res);


                CmsSignedData cms = new CmsSignedData(res);

                var certStore = cms.GetCertificates("Collection");


                SignerInformationStore signers = cms.GetSignerInfos();
                var it = signers.GetSigners().GetEnumerator();
                it.MoveNext();
                var signer = it.Current as SignerInformation;

                var b = signer.Verify(bcCert);
            }
        }
예제 #29
0
        /// <summary>
        /// Verify PKCS7 signature
        /// </summary>
        /// <returns>CAPICOM/CryptoAPI return code or an ApplicationException in file hash doesn't match</returns>
        public bool Verify(ref List <string> ErrorMessageLst)
        {
            bool rc = true;

            //DocsPaUtils.LogsManagement.Debugger.Write("SignedDocument.Verify - INIT");
            try
            {
                // Decodifica un messaggio SignedCms codificato.
                // Al completamento della decodifica, è possibile recuperare le
                // informazioni decodificate dalle proprietà dell'oggetto SignedCms.
                CmsSignedData          cms     = new CmsSignedData(this.GetSignedContent(this._buf));
                IX509Store             store   = cms.GetCertificates("Collection");
                SignerInformationStore signers = cms.GetSignerInfos();


                SignedData da = SignedData.GetInstance(cms.ContentInfo.Content.ToAsn1Object());

                Asn1Sequence DigAlgAsn1 = null;
                if (da.DigestAlgorithms.Count > 0)
                {
                    DigAlgAsn1 = da.DigestAlgorithms[0].ToAsn1Object() as Asn1Sequence;
                }

                if (DigAlgAsn1 != null)
                {
                    this._SignAlgorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID);
                }


                //DocsPaUtils.LogsManagement.Debugger.Write("SignedDocument.Verify - Decode signed message");

                //  Verify signature. Do not validate signer
                //  certificate for the purposes of this example.
                //  Note that in a production environment, validating
                //  the signer certificate chain will probably
                //  be necessary.

                /*
                 * verifica le firme digitali nel messaggio CMS/PKCS #7 firmato e,
                 * facoltativamente, convalida i certificati del firmatario.
                 *
                 * * Se verifySignatureOnly è true, vengono verificate solo le firme digitali.
                 * Se è false, vengono verificate le firme digitali e vengono convalidati
                 * i certificati dei firmatari e gli scopi dei certificati.
                 * Gli scopi di un certificato sono considerati validi se il certificato
                 * non prevede l'utilizzo della chiave o se l'utilizzo della chiave supporta
                 * le firme digitali o il non-rifiuto.
                 *
                 */
                //_signersInfo = new DocsPaVO.documento.SignerInfo[signers.GetSigners().Count];
                //int i = 0;

                List <DocsPaVO.documento.SignerInfo> signInfoLst = new List <DocsPaVO.documento.SignerInfo>();
                foreach (SignerInformation signer in signers.GetSigners())
                {
                    DocsPaVO.documento.SignerInfo thisSinger = ExtractSignerInfo(ErrorMessageLst, store, signer);
                    signInfoLst.Add(thisSinger);
                }

                _signersInfo = signInfoLst.ToArray();
                //DocsPaUtils.LogsManagement.Debugger.Write(string.Format("SignedDocument.Verify - CheckSignature OK, signers count: {0}", signers.GetSigners().Count));
                CmsProcessable signedContent = cms.SignedContent;
                this._content = (byte[])signedContent.GetContent();

                if ((this._SignAlgorithm != null) && this._content != null)
                {
                    try
                    {
                        this._SignHash = BitConverter.ToString(Org.BouncyCastle.Security.DigestUtilities.CalculateDigest(this._SignAlgorithm, this._content)).Replace("-", "");
                    }
                    catch (Exception e)
                    {
                        ErrorMessageLst.Add(e.Message);
                    }
                }

                //DocsPaUtils.LogsManagement.Debugger.Write(string.Format("SignedDocument.Verify - Extact content, lenght: {0}", this._content.Length));

                this._documentFileName = GetDocumentFileName();
                this._SignType         = "CADES";
                //DocsPaUtils.LogsManagement.Debugger.Write(string.Format("SignedDocument.Verify - DocumentFileName: '{0}'", this._documentFileName));
            }
            catch (Exception ex)
            {
                rc = false;
                //DocsPaUtils.LogsManagement.Debugger.Write("SignedDocument.Verify - Si è verificato un errore nella verifica della firma", ex);
                //throw new ApplicationException(ex.Message);
                ErrorMessageLst.Add(ex.Message);
            }
            finally
            {
                //DocsPaUtils.LogsManagement.Debugger.Write("SignedDocument.Verify - END");
            }

            return(rc);
        }
예제 #30
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);
        }
예제 #31
0
        /// <summary>
        /// Verifiy of CRL
        /// </summary>
        /// <param name="fileContents">byte Array file contents</param>
        /// <param name="endPoint">not used </param>
        /// <param name="args">1) Datetime? data verifica / string cachePath / string (bool) nocache</param>
        /// <returns></returns>
        public EsitoVerifica VerificaByteEV(byte[] fileContents, string endPoint, Object[] args)
        {
            //string ID = String.Format("{0}-{1}", Environment.GetEnvironmentVariable("APP_POOL_ID").Replace(" ", ""), AppDomain.CurrentDomain.BaseDirectory);
            bool forceDownload = false;
            //end point lo usiamo per forzare il download

            string p7mSignAlgorithm = null;

            //string p7mSignHash = null;
            DocsPaVO.documento.Internal.SignerInfo[] certSignersInfo;

            EsitoVerifica ev = new EsitoVerifica();

            DateTime?dataverificaDT = null;
            string   cachePath      = string.Empty;

            if (args == null)
            {
                logger.Debug("Args (Date) is null, settign current");
                dataverificaDT = DateTime.Now;
            }
            if (args.Length > 0)
            {
                dataverificaDT = args[0] as DateTime?;
                if (dataverificaDT == null)
                {
                    logger.Debug("Date is null, settign current");
                    dataverificaDT = DateTime.Now;
                }
                cachePath = args[1] as string;

                string fdl = args[2] as string;
                if (!String.IsNullOrEmpty(fdl))
                {
                    Boolean.TryParse(endPoint, out forceDownload);
                }
            }

            int posi = IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("Mime-Version:"));

            if (posi == 0) //E' un mime m7m
            {
                using (MemoryStream ms = new MemoryStream(fileContents))
                {
                    anmar.SharpMimeTools.SharpMessage sm = new anmar.SharpMimeTools.SharpMessage(ms);
                    if (sm.Attachments.Count > 0)
                    {
                        foreach (anmar.SharpMimeTools.SharpAttachment att in sm.Attachments)
                        {
                            if (System.IO.Path.GetExtension(att.Name).ToLower().Contains("p7m"))
                            {
                                att.Stream.Position = 0;
                                BinaryReader sr = new BinaryReader(att.Stream);
                                fileContents = sr.ReadBytes((int)att.Size);
                            }
                        }
                    }
                }
            }

            // Ce provo....
            posi = -1;
            posi = IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("%PDF"));
            if (posi == 0)    //E' un pdf
            {
                PdfReader pdfReader = isPdf(fileContents);
                try
                {
                    AcroFields    af        = pdfReader.AcroFields;
                    List <string> signNames = af.GetSignatureNames();

                    if (signNames.Count == 0) //Firma non è presente
                    {
                        ev.status    = EsitoVerificaStatus.ErroreGenerico;
                        ev.message   = "Il file PDF da verificare non contiene nessuna firma";
                        ev.errorCode = "1458";
                        return(ev);
                    }

                    List <DocsPaVO.documento.Internal.SignerInfo> siList = new List <DocsPaVO.documento.Internal.SignerInfo>();
                    foreach (string name in signNames)
                    {
                        PdfPKCS7 pk = af.VerifySignature(name);
                        p7mSignAlgorithm = pk.GetHashAlgorithm();

                        Org.BouncyCastle.X509.X509Certificate[] certs = pk.Certificates;
                        foreach (X509Certificate cert in certs)
                        {
                            DocsPaVO.documento.Internal.SignerInfo si = GetCertSignersInfo(cert);

                            VerificaValiditaTemporaleCertificato(ev, dataverificaDT, cert, p7mSignAlgorithm);
                            si = ControlloCRL(forceDownload, ev, cachePath, cert, si);

                            siList.Add(si);
                        }
                        bool result = pk.Verify();
                        if (!result)
                        {
                            ev.status    = EsitoVerificaStatus.ErroreGenerico;
                            ev.message   = "La verifica della firma è fallita (File is Tampered)";
                            ev.errorCode = "1450";
                        }
                    }

                    /*
                     * if (
                     *  (pdfReader.PdfVersion.ToString() != "4")||
                     *  (pdfReader.PdfVersion.ToString() != "7"))
                     * {
                     *  ev.status = EsitoVerificaStatus.ErroreGenerico;
                     *  ev.message = "Il file da verificare non è conforme allo standard PDF 1.4 o pdf 1.7";
                     *  ev.errorCode = "1457";
                     * }
                     */

                    List <DocsPaVO.documento.Internal.PKCS7Document> p7docsLst = new List <DocsPaVO.documento.Internal.PKCS7Document>();

                    DocsPaVO.documento.Internal.PKCS7Document p7doc = new DocsPaVO.documento.Internal.PKCS7Document
                    {
                        SignersInfo      = siList.ToArray(),
                        DocumentFileName = null,
                        Level            = 0
                    };
                    p7docsLst.Add(p7doc);

                    ev.VerifySignatureResult = ConvertToVerifySignatureResult(ev.status, p7docsLst.ToArray());
                    ev.content = fileContents;
                }
                catch (Exception e)
                {
                    ev.status    = EsitoVerificaStatus.ErroreGenerico;
                    ev.message   = "Error verifying pdf message :" + e.Message;
                    ev.errorCode = "1402";

                    return(ev);
                }
            }
            else //PKCS7
            {
                try
                {
                    int doclevel = 0;
                    List <DocsPaVO.documento.Internal.PKCS7Document> p7docsLst = new List <DocsPaVO.documento.Internal.PKCS7Document>();
                    do
                    {
                        //questa Estrazione serve solo per capire se uscire dal ciclo ricorsivo e ritornare il content
                        try
                        {
                            ev.content = extractSignedContent(fileContents);
                        }
                        catch
                        {
                            break;
                        }

                        //Ciclo per file firmato
                        Asn1Sequence        sequenza   = Asn1Sequence.GetInstance(fileContents);
                        DerObjectIdentifier tsdOIDFile = sequenza[0] as DerObjectIdentifier;
                        if (tsdOIDFile != null)
                        {
                            if (tsdOIDFile.Id == CmsObjectIdentifiers.timestampedData.Id)   //TSD
                            {
                                logger.Debug("Found TSD file");
                                DerTaggedObject taggedObject = sequenza[1] as DerTaggedObject;
                                if (taggedObject != null)
                                {
                                    Asn1Sequence    asn1seq = Asn1Sequence.GetInstance(taggedObject, true);
                                    TimeStampedData tsd     = TimeStampedData.GetInstance(asn1seq);
                                    fileContents = tsd.Content.GetOctets();
                                }
                            }

                            if (tsdOIDFile.Id == CmsObjectIdentifiers.SignedData.Id)   //p7m
                            {
                                logger.Debug("Found P7M file");
                            }
                        }


                        CmsSignedData cms = new CmsSignedData(fileContents);
                        //controllaCrlFileP7m(cms);

                        IX509Store             store   = cms.GetCertificates("Collection");
                        SignerInformationStore signers = cms.GetSignerInfos();

                        SignedData da = SignedData.GetInstance(cms.ContentInfo.Content.ToAsn1Object());

                        Asn1Sequence DigAlgAsn1 = null;
                        if (da.DigestAlgorithms.Count > 0)
                        {
                            DigAlgAsn1 = da.DigestAlgorithms[0].ToAsn1Object() as Asn1Sequence;
                        }

                        if (DigAlgAsn1 != null)
                        {
                            p7mSignAlgorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID);
                        }

                        certSignersInfo = new DocsPaVO.documento.Internal.SignerInfo[signers.GetSigners().Count];
                        int i = 0;

                        foreach (SignerInformation signer in signers.GetSigners())
                        {
                            bool fileOK = false;
                            Org.BouncyCastle.X509.X509Certificate cert1 = GetCertificate(signer, store);
                            certSignersInfo[i] = GetCertSignersInfo(cert1);
                            VerificaValiditaTemporaleCertificato(ev, dataverificaDT, cert1, p7mSignAlgorithm);

                            fileOK = VerificaNonRepudiation(ev, fileOK, cert1);
                            if (!fileOK)
                            {
                                certSignersInfo[i].CertificateInfo.messages = ev.errorCode + " " + ev.message;
                            }

                            try
                            {
                                fileOK = VerificaCertificato(ev, signer, fileOK, cert1);
                            }
                            catch (Exception e)
                            {
                                ev.status    = EsitoVerificaStatus.ErroreGenerico;
                                ev.message   = "Error verifying 2, message :" + e.Message;
                                ev.errorCode = "1450";
                            }


                            if (fileOK)
                            {
                                certSignersInfo[i] = ControlloCRL(forceDownload, ev, cachePath, cert1, certSignersInfo[i]);
                            }

                            //p7mSignHash = BitConverter.ToString(Org.BouncyCastle.Security.DigestUtilities.CalculateDigest(Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID), (byte[])cms.SignedContent.GetContent())).Replace("-", "");
                        }

                        /*
                         * if (cms.SignedContent != null)
                         * {
                         *  //CmsProcessable signedContent = cms.SignedContent;
                         *  //ev.content = (byte[])signedContent.GetContent();
                         *
                         *  ev.content = extractMatrioskaFile(fileContents);
                         *
                         *
                         *
                         * }
                         */


                        DocsPaVO.documento.Internal.PKCS7Document p7doc = new DocsPaVO.documento.Internal.PKCS7Document
                        {
                            SignersInfo      = certSignersInfo,
                            DocumentFileName = null,
                            Level            = doclevel++
                        };
                        p7docsLst.Add(p7doc);
                        try
                        {
                            fileContents = extractSignedContent(fileContents);
                        }
                        catch
                        {
                            break;
                        }
                    } while (true);

                    ev.VerifySignatureResult = ConvertToVerifySignatureResult(ev.status, p7docsLst.ToArray());;
                }
                catch (Exception e)
                {
                    ev.status    = EsitoVerificaStatus.ErroreGenerico;
                    ev.message   = "Error verifying 1, message :" + e.Message;
                    ev.errorCode = "1402";

                    return(ev);
                }
            }
            return(ev);
        }