/// <summary>
        /// Inserta en la lista de certificados el certificado y comprueba la valided del certificado.
        /// </summary>
        /// <param name="cert"></param>
        /// <param name="unsignedProperties"></param>
        /// <param name="addCertValue"></param>
        /// <param name="extraCerts"></param>
        private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, IEnumerable <OcspServer> ocspServers,
                                    IEnumerable <X509Crl> crlList, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl, X509Certificate2[] extraCerts = null)
        {
            if (addCert)
            {
                if (CertificateChecked(cert, unsignedProperties))
                {
                    return;
                }

                string guidCert = Guid.NewGuid().ToString();

                Cert chainCert = new Cert();
                chainCert.IssuerSerial.X509IssuerName   = cert.IssuerName.Name;
                chainCert.IssuerSerial.X509SerialNumber = cert.GetSerialNumberAsDecimalString();
                DigestUtil.SetCertDigest(cert.GetRawCertData(), digestMethod, chainCert.CertDigest);
                chainCert.URI = "#Cert" + guidCert;
                unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(chainCert);

                EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate();
                encapsulatedX509Certificate.Id      = "Cert" + guidCert;
                encapsulatedX509Certificate.PkiData = cert.GetRawCertData();
                unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate);
            }

            var chain = CertUtil.GetCertChain(cert, extraCerts).ChainElements;

            if (chain.Count > 1)
            {
                X509ChainElementEnumerator enumerator = chain.GetEnumerator();
                enumerator.MoveNext(); // el mismo certificado que el pasado por parametro

                enumerator.MoveNext();

                bool valid = ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate, crlList, digestMethod);

                if (!valid)
                {
                    var ocspCerts = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate, ocspServers, digestMethod, addCertificateOcspUrl);

                    if (ocspCerts != null)
                    {
                        X509Certificate2 startOcspCert = DetermineStartCert(ocspCerts);

                        if (!EquivalentDN(startOcspCert.IssuerName, enumerator.Current.Certificate.SubjectName))
                        {
                            var chainOcsp = CertUtil.GetCertChain(startOcspCert, ocspCerts);

                            AddCertificate(chainOcsp.ChainElements[1].Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, addCertificateOcspUrl, ocspCerts);
                        }
                    }
                }

                AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, addCertificateOcspUrl, extraCerts);
            }
        }
Esempio n. 2
0
 private bool CertificateChecked(X509Certificate2 cert, UnsignedProperties unsignedProperties)
 {
     foreach (EncapsulatedX509Certificate item in unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection)
     {
         X509Certificate2 x509Certificate = new X509Certificate2(item.PkiData);
         if (x509Certificate.SubjectName.Equals(cert.SubjectName))
         {
             return(true);
         }
     }
     return(false);
 }
Esempio n. 3
0
        private bool ValidateCertificateByCRL(UnsignedProperties unsignedProperties, X509Certificate2 certificate, X509Certificate2 issuer,
                                              IEnumerable <X509Crl> crlList, FirmaXadesNet.Crypto.DigestMethod digestMethod)
        {
            Org.BouncyCastle.X509.X509Certificate clientCert = certificate.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate issuerCert = issuer.ToBouncyX509Certificate();

            foreach (var crlEntry in crlList)
            {
                if (crlEntry.IssuerDN.Equivalent(issuerCert.SubjectDN) && crlEntry.NextUpdate.Value > DateTime.Now)
                {
                    if (!crlEntry.IsRevoked(clientCert))
                    {
                        if (!ExistsCRL(unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection,
                                       issuer.Subject))
                        {
                            string idCrlValue = "CRLValue-" + Guid.NewGuid().ToString();

                            CRLRef crlRef = new CRLRef();
                            crlRef.CRLIdentifier.UriAttribute = "#" + idCrlValue;
                            crlRef.CRLIdentifier.Issuer       = issuer.Subject;
                            crlRef.CRLIdentifier.IssueTime    = crlEntry.ThisUpdate.ToLocalTime();

                            var crlNumber = GetCRLNumber(crlEntry);
                            if (crlNumber.HasValue)
                            {
                                crlRef.CRLIdentifier.Number = crlNumber.Value;
                            }

                            byte[] crlEncoded = crlEntry.GetEncoded();
                            DigestUtil.SetCertDigest(crlEncoded, digestMethod, crlRef.CertDigest);

                            CRLValue crlValue = new CRLValue
                            {
                                PkiData = crlEncoded,
                                Id      = idCrlValue
                            };

                            unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection.Add(crlRef);
                            unsignedProperties.UnsignedSignatureProperties.RevocationValues.CRLValues.CRLValueCollection.Add(crlValue);
                        }

                        return(true);
                    }
                    else
                    {
                        throw new Exception("Certificate revoked");
                    }
                }
            }

            return(false);
        }
        /// <summary>
        /// Determina si un certificado ya ha sido añadido a la colección de certificados
        /// </summary>
        /// <param name="cert"></param>
        /// <param name="unsignedProperties"></param>
        /// <returns></returns>
        private bool CertificateChecked(X509Certificate2 cert, UnsignedProperties unsignedProperties)
        {
            foreach (EncapsulatedX509Certificate item in unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection)
            {
                X509Certificate2 certItem = new X509Certificate2(item.PkiData);

                if (certItem.Thumbprint == cert.Thumbprint)
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 5
0
        private void AddTSACertificates(UnsignedProperties unsignedProperties, IEnumerable <string> ocspServers, IEnumerable <X509Crl> crlList, FirmaXades.Crypto.DigestMethod digestMethod)
        {
            TimeStampToken          timeStampToken = new TimeStampToken(new CmsSignedData(unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection[0].EncapsulatedTimeStamp.PkiData));
            IX509Store              certificates   = timeStampToken.GetCertificates("Collection");
            SignerID                signerID       = timeStampToken.SignerID;
            List <X509Certificate2> list           = new List <X509Certificate2>();

            foreach (object match in certificates.GetMatches(null))
            {
                X509Certificate2 item = new X509Certificate2(((Org.BouncyCastle.X509.X509Certificate)match).GetEncoded());
                list.Add(item);
            }
            X509Certificate2 cert = DetermineStartCert(list);

            AddCertificate(cert, unsignedProperties, true, ocspServers, crlList, digestMethod, list.ToArray());
        }
Esempio n. 6
0
        private void TimeStampCertRefs(SignatureDocument signatureDocument, UpgradeParameters parameters)
        {
            TimeStamp xadesXTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[] signatureValueHash;

            XmlElement nodoFirma = signatureDocument.XadesSignature.GetSignatureElement();

            XmlNamespaceManager nm = new XmlNamespaceManager(signatureDocument.Document.NameTable);

            nm.AddNamespace("xades", XadesSignedXml.XadesNamespaceUri);
            nm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            XmlNode xmlCompleteCertRefs = nodoFirma.SelectSingleNode("ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CompleteCertificateRefs", nm);

            if (xmlCompleteCertRefs == null)
            {
                signatureDocument.UpdateDocument();
            }

            signatureValueElementXpaths = new ArrayList
            {
                "ds:SignatureValue",
                "ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:SignatureTimeStamp",
                "ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CompleteCertificateRefs",
                "ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CompleteRevocationRefs"
            };
            signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(signatureDocument.XadesSignature, signatureValueElementXpaths), parameters.DigestMethod);

            byte[] tsa = parameters.TimeStampClient.GetTimeStamp(signatureValueHash, parameters.DigestMethod, true);

            xadesXTimeStamp = new TimeStamp("SigAndRefsTimeStamp")
            {
                Id = "SigAndRefsStamp-" + signatureDocument.XadesSignature.Signature.Id
            };
            xadesXTimeStamp.EncapsulatedTimeStamp.PkiData = tsa;
            xadesXTimeStamp.EncapsulatedTimeStamp.Id      = "SigAndRefsStamp-" + Guid.NewGuid().ToString();
            UnsignedProperties unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.RefsOnlyTimeStampFlag = false;
            unsignedProperties.UnsignedSignatureProperties.SigAndRefsTimeStampCollection.Add(xadesXTimeStamp);


            signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;
        }
Esempio n. 7
0
        /// <summary>
        /// Inserta y valida los certificados del servidor de sellado de tiempo.
        /// </summary>
        /// <param name="unsignedProperties"></param>
        private void AddTSACertificates(UnsignedProperties unsignedProperties)
        {
            TimeStampToken token = new TimeStampToken(new Org.BouncyCastle.Cms.CmsSignedData(unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection[0].EncapsulatedTimeStamp.PkiData));
            IX509Store     store = token.GetCertificates("Collection");

            Org.BouncyCastle.Cms.SignerID signerId = token.SignerID;

            List <X509Certificate2> tsaCerts = new List <X509Certificate2>();

            foreach (var tsaCert in store.GetMatches(null))
            {
                X509Certificate2 cert = new X509Certificate2(((Org.BouncyCastle.X509.X509Certificate)tsaCert).GetEncoded());
                tsaCerts.Add(cert);
            }

            X509Certificate2 startCert = DetermineStartCert(tsaCerts);

            AddCertificate(startCert, unsignedProperties, true, tsaCerts.ToArray());
        }
Esempio n. 8
0
        /// <summary>
        /// Determina si un certificado ya ha sido añadido a la colección de certificados
        /// </summary>
        /// <param name="cert"></param>
        /// <param name="unsignedProperties"></param>
        /// <returns></returns>
        private bool CertificateChecked(X509Certificate2 cert, UnsignedProperties unsignedProperties)
        {
            string certHash = null;

            using (var hashAlg = DigestUtil.GetHashAlg(_firma.RefsDigestMethod))
            {
                certHash = Convert.ToBase64String(hashAlg.ComputeHash(cert.GetRawCertData()));
            }

            foreach (Cert item in unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection)
            {
                if (Convert.ToBase64String(item.CertDigest.DigestValue) == certHash)
                {
                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        /// Inserta y valida los certificados del servidor de sellado de tiempo.
        /// </summary>
        /// <param name="unsignedProperties"></param>
        private void AddTSACertificates(UnsignedProperties unsignedProperties, IEnumerable <OcspServer> ocspServers, IEnumerable <X509Crl> crlList, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl)
        {
            TimeStampToken token = new TimeStampToken(new CmsSignedData(unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection[0].EncapsulatedTimeStamp.PkiData));
            IX509Store     store = token.GetCertificates("Collection");

            Org.BouncyCastle.Cms.SignerID signerId = token.SignerID;

            List <X509Certificate2> tsaCerts = new List <X509Certificate2>();

            foreach (var tsaCert in store.GetMatches(null))
            {
                X509Certificate2 cert = new X509Certificate2(((Org.BouncyCastle.X509.X509Certificate)tsaCert).GetEncoded());
                tsaCerts.Add(cert);
            }

            X509Certificate2 startCert = DetermineStartCert(tsaCerts.ToArray());

            AddCertificate(startCert, unsignedProperties, true, ocspServers, crlList, digestMethod, addCertificateOcspUrl, tsaCerts.ToArray());
        }
Esempio n. 10
0
        private void AddCertificate(X509Certificate2 cert, UnsignedProperties unsignedProperties, bool addCert, IEnumerable <string> ocspServers, IEnumerable <X509Crl> crlList, FirmaXades.Crypto.DigestMethod digestMethod, X509Certificate2[] extraCerts = null)
        {
            if (addCert)
            {
                if (CertificateChecked(cert, unsignedProperties))
                {
                    return;
                }
                string str   = Guid.NewGuid().ToString();
                Cert   cert2 = new Cert();
                cert2.IssuerSerial.X509IssuerName   = cert.IssuerName.Name;
                cert2.IssuerSerial.X509SerialNumber = cert.GetSerialNumberAsDecimalString();
                DigestUtil.SetCertDigest(cert.GetRawCertData(), digestMethod, cert2.CertDigest);
                cert2.URI = "#Cert" + str;
                unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection.Add(cert2);
                EncapsulatedX509Certificate encapsulatedX509Certificate = new EncapsulatedX509Certificate();
                encapsulatedX509Certificate.Id      = "Cert" + str;
                encapsulatedX509Certificate.PkiData = cert.GetRawCertData();
                unsignedProperties.UnsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate);
            }
            X509ChainElementCollection chainElements = CertUtil.GetCertChain(cert, extraCerts).ChainElements;

            if (chainElements.Count > 1)
            {
                X509ChainElementEnumerator enumerator = chainElements.GetEnumerator();
                enumerator.MoveNext();
                enumerator.MoveNext();
                if (!ValidateCertificateByCRL(unsignedProperties, cert, enumerator.Current.Certificate, crlList, digestMethod))
                {
                    X509Certificate2[] array = ValidateCertificateByOCSP(unsignedProperties, cert, enumerator.Current.Certificate, ocspServers, digestMethod);
                    if (array != null)
                    {
                        X509Certificate2 x509Certificate = DetermineStartCert(new List <X509Certificate2>(array));
                        if (x509Certificate.IssuerName.Name != enumerator.Current.Certificate.SubjectName.Name)
                        {
                            X509Chain certChain = CertUtil.GetCertChain(x509Certificate, array);
                            AddCertificate(certChain.ChainElements[1].Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, array);
                        }
                    }
                }
                AddCertificate(enumerator.Current.Certificate, unsignedProperties, true, ocspServers, crlList, digestMethod, extraCerts);
            }
        }
        public void Upgrade(SignatureDocument signatureDocument, UpgradeParameters parameters)
        {
            TimeStamp signatureTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[]             signatureValueHash;
            UnsignedProperties unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;

            try
            {
                if (unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Count > 0)
                {
                    throw new Exception("The signature already contains a time stamp");
                }

                signatureValueElementXpaths = new ArrayList
                {
                    "ds:SignatureValue"
                };
                signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(signatureDocument.XadesSignature, signatureValueElementXpaths), parameters.DigestMethod);

                byte[] tsa = parameters.TimeStampClient.GetTimeStamp(signatureValueHash, parameters.DigestMethod, true);

                signatureTimeStamp = new TimeStamp("SignatureTimeStamp")
                {
                    Id = "SignatureTimeStamp-" + signatureDocument.XadesSignature.Signature.Id
                };
                signatureTimeStamp.EncapsulatedTimeStamp.PkiData = tsa;
                signatureTimeStamp.EncapsulatedTimeStamp.Id      = "SignatureTimeStamp-" + Guid.NewGuid().ToString();

                unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Add(signatureTimeStamp);

                signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;

                signatureDocument.UpdateDocument();
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while inserting the time stamp", ex);
            }
        }
Esempio n. 12
0
        public void Upgrade(SignatureDocument signatureDocument, UpgradeParameters parameters)
        {
            TimeStamp signatureTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[]             signatureValueHash;
            UnsignedProperties unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;

            try
            {
                if (unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Count > 0)
                {
                    throw new Exception("La firma ya contiene un sello de tiempo");
                }

                XmlDsigExcC14NTransform excTransform = new XmlDsigExcC14NTransform();

                signatureValueElementXpaths = new ArrayList();
                signatureValueElementXpaths.Add("ds:SignatureValue");
                signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(signatureDocument.XadesSignature, signatureValueElementXpaths, excTransform), parameters.DigestMethod);

                byte[] tsa = parameters.TimeStampClient.GetTimeStamp(signatureValueHash, parameters.DigestMethod, true);

                signatureTimeStamp    = new TimeStamp("SignatureTimeStamp");
                signatureTimeStamp.Id = "SignatureTimeStamp-" + signatureDocument.XadesSignature.Signature.Id;
                signatureTimeStamp.CanonicalizationMethod           = new CanonicalizationMethod();
                signatureTimeStamp.CanonicalizationMethod.Algorithm = excTransform.Algorithm;
                signatureTimeStamp.EncapsulatedTimeStamp.PkiData    = tsa;
                signatureTimeStamp.EncapsulatedTimeStamp.Id         = "SignatureTimeStamp-" + Guid.NewGuid().ToString();

                unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Add(signatureTimeStamp);

                signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;

                signatureDocument.UpdateDocument();
            }
            catch (Exception ex)
            {
                throw new Exception("Ha ocurrido un error al insertar el sellado de tiempo.", ex);
            }
        }
Esempio n. 13
0
        private void InjectXadesXInformation(XadesSignedXml xadesSignedXml)
        {
            TimeStamp xadesXTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[] signatureValueHash;
            byte[] tsaTimeStamp;

            signatureValueElementXpaths = new ArrayList();

            signatureValueElementXpaths.Add("ds:Object/xsd:QualifyingProperties/xsd:UnsignedProperties/xsd:UnsignedSignatureProperties/xsd:CompleteCertificateRefs");
            signatureValueElementXpaths.Add("ds:Object/xsd:QualifyingProperties/xsd:UnsignedProperties/xsd:UnsignedSignatureProperties/xsd:CompleteRevocationRefs");

            signatureValueHash = ComputeHashValueOfElementList(xadesSignedXml.GetXml(), signatureValueElementXpaths);

            //jbonilla
            tsaTimeStamp    = this.tspSource.GetTimeStampToken(signatureValueHash);
            xadesXTimeStamp = new TimeStamp("RefsOnlyTimeStamp");

            xadesXTimeStamp.EncapsulatedTimeStamp.PkiData    = tsaTimeStamp;
            xadesXTimeStamp.CanonicalizationMethod.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl;
            //xadesXTimeStamp.EncapsulatedTimeStamp.Id = "";

            //jbonilla Deprecated
            //foreach (string elementIdValue in elementIdValues)
            //{
            //    hashDataInfo = new HashDataInfo();
            //    hashDataInfo.UriAttribute = "#" + elementIdValue;
            //    xadesXTimeStamp.HashDataInfoCollection.Add(hashDataInfo);
            //}

            UnsignedProperties unsignedProperties = xadesSignedXml.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.RefsOnlyTimeStampFlag = true;
            unsignedProperties.UnsignedSignatureProperties.RefsOnlyTimeStampCollection.Add(xadesXTimeStamp);

            xadesSignedXml.UnsignedProperties = unsignedProperties;
        }
Esempio n. 14
0
        public override void Upgrade()
        {
            TimeStamp signatureTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[]             signatureValueHash;
            UnsignedProperties unsignedProperties = _firma.XadesSignature.UnsignedProperties;

            try
            {
                if (unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Count > 0)
                {
                    throw new Exception("La firma ya contiene un sello de tiempo");
                }

                signatureValueElementXpaths = new ArrayList();
                signatureValueElementXpaths.Add("ds:SignatureValue");
                signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(_firma.XadesSignature, signatureValueElementXpaths), DigestMethod.SHA1);

                byte[] tsa = TimeStampClient.GetTimeStamp(_firma.TSAServer, signatureValueHash, DigestMethod.SHA1, true);

                signatureTimeStamp    = new TimeStamp("SignatureTimeStamp");
                signatureTimeStamp.Id = "SignatureTimeStamp-" + _firma.XadesSignature.Signature.Id;
                signatureTimeStamp.EncapsulatedTimeStamp.PkiData = tsa;
                signatureTimeStamp.EncapsulatedTimeStamp.Id      = "SignatureTimeStamp-" + Guid.NewGuid().ToString();

                unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Add(signatureTimeStamp);

                _firma.XadesSignature.UnsignedProperties = unsignedProperties;

                _firma.UpdateDocument();
            }
            catch (Exception ex)
            {
                throw new Exception("Ha ocurrido un error al insertar el sellado de tiempo.", ex);
            }
        }
Esempio n. 15
0
        public void Upgrade(SignatureDocument signatureDocument, UpgradeParameters parameters)
        {
            UnsignedProperties unsignedProperties = null;
            CertificateValues  certificateValues  = null;

            X509Certificate2 signingCertificate = signatureDocument.XadesSignature.GetSigningCertificate();

            unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;
            unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs = new CompleteCertificateRefs
            {
                Id = "CompleteCertificates-" + Guid.NewGuid().ToString()
            };

            unsignedProperties.UnsignedSignatureProperties.CertificateValues = new CertificateValues();
            certificateValues    = unsignedProperties.UnsignedSignatureProperties.CertificateValues;
            certificateValues.Id = "CertificatesValues-" + Guid.NewGuid().ToString();

            unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs = new CompleteRevocationRefs
            {
                Id = "CompleteRev-" + Guid.NewGuid().ToString()
            };

            unsignedProperties.UnsignedSignatureProperties.RevocationValues = new RevocationValues
            {
                Id = "RevocationValues-" + Guid.NewGuid().ToString()
            };

            AddCertificate(signingCertificate, unsignedProperties, false, parameters.OCSPServers, parameters.CRL, parameters.DigestMethod, parameters.GetOcspUrlFromCertificate);

            AddTSACertificates(unsignedProperties, parameters.OCSPServers, parameters.CRL, parameters.DigestMethod, parameters.GetOcspUrlFromCertificate);

            signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;

            TimeStampCertRefs(signatureDocument, parameters);

            signatureDocument.UpdateDocument();
        }
Esempio n. 16
0
 private bool ValidateCertificateByCRL(UnsignedProperties unsignedProperties, X509Certificate2 certificate, X509Certificate2 issuer, IEnumerable <X509Crl> crlList, FirmaXades.Crypto.DigestMethod digestMethod)
 {
     Org.BouncyCastle.X509.X509Certificate cert            = certificate.ToBouncyX509Certificate();
     Org.BouncyCastle.X509.X509Certificate x509Certificate = issuer.ToBouncyX509Certificate();
     foreach (X509Crl crl in crlList)
     {
         if (crl.IssuerDN.Equivalent(x509Certificate.SubjectDN) && crl.NextUpdate.Value > DateTime.Now)
         {
             if (crl.IsRevoked(cert))
             {
                 throw new Exception("Certificado revocado");
             }
             if (!ExistsCRL(unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection, issuer.Subject))
             {
                 string text   = "CRLValue-" + Guid.NewGuid().ToString();
                 CRLRef cRLRef = new CRLRef();
                 cRLRef.CRLIdentifier.UriAttribute = "#" + text;
                 cRLRef.CRLIdentifier.Issuer       = issuer.Subject;
                 cRLRef.CRLIdentifier.IssueTime    = crl.ThisUpdate.ToLocalTime();
                 long?cRLNumber = GetCRLNumber(crl);
                 if (cRLNumber.HasValue)
                 {
                     cRLRef.CRLIdentifier.Number = cRLNumber.Value;
                 }
                 byte[] encoded = crl.GetEncoded();
                 DigestUtil.SetCertDigest(encoded, digestMethod, cRLRef.CertDigest);
                 CRLValue cRLValue = new CRLValue();
                 cRLValue.PkiData = encoded;
                 cRLValue.Id      = text;
                 unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection.Add(cRLRef);
                 unsignedProperties.UnsignedSignatureProperties.RevocationValues.CRLValues.CRLValueCollection.Add(cRLValue);
             }
             return(true);
         }
     }
     return(false);
 }
        private X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer,
                                                             IEnumerable <OcspServer> ocspServers, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl)
        {
            bool byKey = false;
            List <OcspServer> finalOcspServers = new List <OcspServer>();

            Org.BouncyCastle.X509.X509Certificate clientCert = client.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate issuerCert = issuer.ToBouncyX509Certificate();

            OcspClient ocsp = new OcspClient();

            if (addCertificateOcspUrl)
            {
                string certOcspUrl = ocsp.GetAuthorityInformationAccessOcspUrl(issuerCert);

                if (!string.IsNullOrEmpty(certOcspUrl))
                {
                    finalOcspServers.Add(new OcspServer(certOcspUrl));
                }
            }

            foreach (var ocspServer in ocspServers)
            {
                finalOcspServers.Add(ocspServer);
            }

            foreach (var ocspServer in finalOcspServers)
            {
                byte[] resp = ocsp.QueryBinary(clientCert, issuerCert, ocspServer.Url, ocspServer.RequestorName,
                                               ocspServer.SignCertificate);

                FirmaXadesNet.Clients.CertificateStatus status = ocsp.ProcessOcspResponse(resp);

                if (status == FirmaXadesNet.Clients.CertificateStatus.Revoked)
                {
                    throw new Exception("Certificado revocado");
                }
                else if (status == FirmaXadesNet.Clients.CertificateStatus.Good)
                {
                    Org.BouncyCastle.Ocsp.OcspResp r = new OcspResp(resp);
                    byte[]        rEncoded           = r.GetEncoded();
                    BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();

                    string guidOcsp = Guid.NewGuid().ToString();

                    OCSPRef ocspRef = new OCSPRef();
                    ocspRef.OCSPIdentifier.UriAttribute = "#OcspValue" + guidOcsp;
                    DigestUtil.SetCertDigest(rEncoded, digestMethod, ocspRef.CertDigest);

                    ResponderID rpId = or.ResponderId.ToAsn1Object();
                    ocspRef.OCSPIdentifier.ResponderID = GetResponderName(rpId, ref byKey);
                    ocspRef.OCSPIdentifier.ByKey       = byKey;

                    ocspRef.OCSPIdentifier.ProducedAt = or.ProducedAt.ToLocalTime();
                    unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.OCSPRefs.OCSPRefCollection.Add(ocspRef);

                    OCSPValue ocspValue = new OCSPValue();
                    ocspValue.PkiData = rEncoded;
                    ocspValue.Id      = "OcspValue" + guidOcsp;
                    unsignedProperties.UnsignedSignatureProperties.RevocationValues.OCSPValues.OCSPValueCollection.Add(ocspValue);

                    return((from cert in or.GetCerts()
                            select new X509Certificate2(cert.GetEncoded())).ToArray());
                }
            }

            throw new Exception("El certificado no ha podido ser validado");
        }
Esempio n. 18
0
        protected internal override void ExtendSignatureTag(XadesSignedXml xadesSignedXml)
        {
            base.ExtendSignatureTag(xadesSignedXml);

            X509Certificate signingCertificate = DotNetUtilities.FromX509Certificate(
                xadesSignedXml.GetSigningCertificate());

            DateTime signingTime = xadesSignedXml.XadesObject.QualifyingProperties
                                   .SignedProperties.SignedSignatureProperties.SigningTime;

            ValidationContext ctx = certificateVerifier.ValidateCertificate(signingCertificate
                                                                            , signingTime, new XAdESCertificateSource(xadesSignedXml.GetXml(), false), null, null);

            UnsignedProperties unsignedProperties = null;
            //int certificateValuesCounter;
            CertificateValues           certificateValues;
            EncapsulatedX509Certificate encapsulatedX509Certificate;
            RevocationValues            revocationValues;
            CRLValue  newCRLValue;
            OCSPValue newOCSPValue;

            unsignedProperties = xadesSignedXml.UnsignedProperties;

            //TODO jbonilla Validate certificate refs.
            {
                unsignedProperties.UnsignedSignatureProperties.CertificateValues = new CertificateValues();
                certificateValues = unsignedProperties.UnsignedSignatureProperties.CertificateValues;
                //certificateValues.Id = this.certificateValuesIdTextBox.Text;
                //certificateValuesCounter = 0;

                foreach (CertificateAndContext certificate in ctx.GetNeededCertificates())
                {
                    encapsulatedX509Certificate = new EncapsulatedX509Certificate();
                    //encapsulatedX509Certificate.Id = this.certificateValuesIdTextBox.Text + certificateValuesCounter.ToString();
                    encapsulatedX509Certificate.PkiData = certificate.GetCertificate().GetEncoded();
                    //certificateValuesCounter++;
                    certificateValues.EncapsulatedX509CertificateCollection.Add(encapsulatedX509Certificate);
                }
            }

            unsignedProperties = xadesSignedXml.UnsignedProperties;
            unsignedProperties.UnsignedSignatureProperties.RevocationValues = new RevocationValues();
            revocationValues = unsignedProperties.UnsignedSignatureProperties.RevocationValues;
            //revocationValues.Id = this.revocationValuesIdTextBox.Text;

            if (ctx.GetNeededOCSPResp().Count > 0)
            {
                foreach (BasicOcspResp ocsp in ctx.GetNeededOCSPResp())
                {
                    newOCSPValue         = new OCSPValue();
                    newOCSPValue.PkiData = OCSPUtils.FromBasicToResp(ocsp).GetEncoded();
                    revocationValues.OCSPValues.OCSPValueCollection.Add(newOCSPValue);
                }
            }

            if (ctx.GetNeededCRL().Count > 0)
            {
                foreach (X509Crl crl in ctx.GetNeededCRL())
                {
                    newCRLValue         = new CRLValue();
                    newCRLValue.PkiData = crl.GetEncoded();
                    revocationValues.CRLValues.CRLValueCollection.Add(newCRLValue);
                }
            }

            xadesSignedXml.UnsignedProperties = unsignedProperties;
        }
Esempio n. 19
0
        /// <summary>
        /// Realiza la contrafirma de la firma actual
        /// </summary>
        /// <param name="sigDocument"></param>
        /// <param name="parameters"></param>
        public SignatureDocument CounterSign(SignatureDocument sigDocument, SignatureParameters parameters)
        {
            if (parameters.Signer == null)
            {
                throw new Exception("A valid certificate is required for the signature");
            }

            SignatureDocument.CheckSignatureDocument(sigDocument);

            SignatureDocument counterSigDocument = new SignatureDocument
            {
                Document = (XmlDocument)sigDocument.Document.Clone()
            };

            counterSigDocument.Document.PreserveWhitespace = true;

            XadesSignedXml counterSignature = new XadesSignedXml(counterSigDocument.Document);

            SetSignatureId(counterSignature);

            counterSignature.SigningKey = parameters.Signer.SigningKey;

            _refContent = new Reference
            {
                Uri  = "#" + sigDocument.XadesSignature.SignatureValueId,
                Id   = "Reference-" + Guid.NewGuid().ToString(),
                Type = "http://uri.etsi.org/01903#CountersignedSignature"
            };
            _refContent.AddTransform(new XmlDsigC14NTransform());
            counterSignature.AddReference(_refContent);

            _mimeType = "text/xml";
            _encoding = "UTF-8";

            KeyInfo keyInfo = new KeyInfo
            {
                Id = "KeyInfoId-" + counterSignature.Signature.Id
            };

            keyInfo.AddClause(new KeyInfoX509Data((X509Certificate)parameters.Signer.Certificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)parameters.Signer.SigningKey));
            counterSignature.KeyInfo = keyInfo;

            Reference referenceKeyInfo = new Reference
            {
                Id  = "ReferenceKeyInfo-" + counterSignature.Signature.Id,
                Uri = "#KeyInfoId-" + counterSignature.Signature.Id
            };

            counterSignature.AddReference(referenceKeyInfo);

            XadesObject counterSignatureXadesObject = new XadesObject
            {
                Id = "CounterSignatureXadesObject-" + Guid.NewGuid().ToString()
            };

            counterSignatureXadesObject.QualifyingProperties.Target = "#" + counterSignature.Signature.Id;
            counterSignatureXadesObject.QualifyingProperties.SignedProperties.Id = "SignedProperties-" + counterSignature.Signature.Id;

            AddSignatureProperties(counterSigDocument, counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                                   counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                                   counterSignatureXadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties, parameters);

            counterSignature.AddXadesObject(counterSignatureXadesObject);

            foreach (Reference signReference in counterSignature.SignedInfo.References)
            {
                signReference.DigestMethod = parameters.DigestMethod.URI;
            }

            counterSignature.SignedInfo.SignatureMethod = parameters.SignatureMethod.URI;

            counterSignature.AddXadesNamespace = true;
            counterSignature.ComputeSignature();

            counterSigDocument.XadesSignature = new XadesSignedXml(counterSigDocument.Document);
            counterSigDocument.XadesSignature.LoadXml(sigDocument.XadesSignature.GetXml());

            UnsignedProperties unsignedProperties = counterSigDocument.XadesSignature.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection.Add(counterSignature);
            counterSigDocument.XadesSignature.UnsignedProperties = unsignedProperties;

            counterSigDocument.UpdateDocument();

            return(counterSigDocument);
        }
Esempio n. 20
0
        /// <summary>
        /// Realiza la contrafirma de la firma actual
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="signMethod"></param>
        public void CounterSign(X509Certificate2 certificate, SignMethod?signMethod = null)
        {
            SetSignatureId();

            if (_xadesSignedXml == null)
            {
                throw new Exception("No hay ninguna firma XADES cargada previamente.");
            }

            if (certificate == null)
            {
                throw new Exception("Es necesario un certificado válido para la firma.");
            }

            if (signMethod.HasValue)
            {
                this.SignMethod = signMethod.Value;
            }

            _signCertificate = certificate;

            XadesSignedXml counterSignature = new XadesSignedXml(_document);

            SetCryptoServiceProvider();

            counterSignature.SigningKey = _rsaKey;

            Reference reference = new Reference();

            reference.Uri  = "#" + _xadesSignedXml.SignatureValueId;
            reference.Id   = "Reference-" + Guid.NewGuid().ToString();
            reference.Type = "http://uri.etsi.org/01903#CountersignedSignature";
            reference.AddTransform(new XmlDsigC14NTransform());
            counterSignature.AddReference(reference);
            _objectReference = reference.Id;

            KeyInfo keyInfo = new KeyInfo();

            keyInfo.Id = "KeyInfoId-" + _signatureId;
            keyInfo.AddClause(new KeyInfoX509Data((X509Certificate)_signCertificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)_rsaKey));
            counterSignature.KeyInfo = keyInfo;

            Reference referenceKeyInfo = new Reference();

            referenceKeyInfo.Id  = "ReferenceKeyInfo-" + _signatureId;
            referenceKeyInfo.Uri = "#KeyInfoId-" + _signatureId;
            counterSignature.AddReference(referenceKeyInfo);

            counterSignature.Signature.Id     = _signatureId;
            counterSignature.SignatureValueId = _signatureValueId;

            XadesObject counterSignatureXadesObject = new XadesObject();

            counterSignatureXadesObject.Id = "CounterSignatureXadesObject-" + Guid.NewGuid().ToString();
            counterSignatureXadesObject.QualifyingProperties.Target = "#" + _signatureId;
            counterSignatureXadesObject.QualifyingProperties.SignedProperties.Id = "SignedProperties-" + _signatureId;

            AddSignatureProperties(counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                                   counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                                   counterSignatureXadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties,
                                   "text/xml", _signCertificate);

            counterSignature.AddXadesObject(counterSignatureXadesObject);

            foreach (Reference signReference in counterSignature.SignedInfo.References)
            {
                signReference.DigestMethod = _refsMethodUri;
            }

            counterSignature.AddXadesNamespace = true;
            counterSignature.ComputeSignature();

            UnsignedProperties unsignedProperties = _xadesSignedXml.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection.Add(counterSignature);
            _xadesSignedXml.UnsignedProperties = unsignedProperties;

            UpdateDocument();

            _xadesSignedXml = new XadesSignedXml(_document);

            XmlNode xmlNode = _document.SelectSingleNode("//*[@Id='" + _signatureId + "']");

            _xadesSignedXml.LoadXml((XmlElement)xmlNode);
        }
        /// <summary>
        /// Realiza la contrafirma de la firma actual
        /// </summary>
        /// <param name="sigDocument"></param>
        /// <param name="parameters"></param>
        public SignatureDocument CounterSign(SignatureDocument sigDocument, SignatureParameters parameters)
        {
            if (parameters.Signer == null)
            {
                throw new Exception("Es necesario un certificado válido para la firma.");
            }

            SignatureDocument.CheckSignatureDocument(sigDocument);

            SignatureDocument counterSigDocument = new SignatureDocument();

            counterSigDocument.Document = (XmlDocument)sigDocument.Document.Clone();
            counterSigDocument.Document.PreserveWhitespace = true;

            XadesSignedXml counterSignature = new XadesSignedXml(counterSigDocument.Document);

            SetSignatureId(counterSignature);

            counterSignature.SigningKey = parameters.Signer.SigningKey;

            _refContent      = new Reference();
            _refContent.Uri  = "#" + sigDocument.XadesSignature.SignatureValueId;
            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Type = "http://uri.etsi.org/01903#CountersignedSignature";
            _refContent.AddTransform(new XmlDsigC14NTransform());
            counterSignature.AddReference(_refContent);

            _dataFormat          = new DataObjectFormat();
            _dataFormat.MimeType = "text/xml";
            _dataFormat.Encoding = "UTF-8";

            KeyInfo keyInfo = new KeyInfo();

            keyInfo.Id = "KeyInfoId-" + counterSignature.Signature.Id;
            keyInfo.AddClause(new KeyInfoX509Data((X509Certificate)parameters.Signer.Certificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)parameters.Signer.SigningKey));
            counterSignature.KeyInfo = keyInfo;

            Reference referenceKeyInfo = new Reference();

            referenceKeyInfo.Id  = "ReferenceKeyInfo-" + counterSignature.Signature.Id;
            referenceKeyInfo.Uri = "#KeyInfoId-" + counterSignature.Signature.Id;
            counterSignature.AddReference(referenceKeyInfo);

            XadesObject counterSignatureXadesObject = new XadesObject();

            counterSignatureXadesObject.Id = "CounterSignatureXadesObject-" + Guid.NewGuid().ToString();
            counterSignatureXadesObject.QualifyingProperties.Target = "#" + counterSignature.Signature.Id;
            counterSignatureXadesObject.QualifyingProperties.SignedProperties.Id = "SignedProperties-" + counterSignature.Signature.Id;

            AddSignatureProperties(counterSigDocument, counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                                   counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                                   counterSignatureXadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties, parameters);

            counterSignature.AddXadesObject(counterSignatureXadesObject);

            foreach (Reference signReference in counterSignature.SignedInfo.References)
            {
                signReference.DigestMethod = parameters.DigestMethod.URI;
            }

            counterSignature.SignedInfo.SignatureMethod = parameters.SignatureMethod.URI;

            counterSignature.AddXadesNamespace = true;
            counterSignature.ComputeSignature();

            UnsignedProperties unsignedProperties = sigDocument.XadesSignature.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection.Add(counterSignature);
            sigDocument.XadesSignature.UnsignedProperties = unsignedProperties;

            UpdateXadesSignature(sigDocument);

            counterSigDocument.Document = (XmlDocument)sigDocument.Document.Clone();
            counterSigDocument.Document.PreserveWhitespace = true;

            XmlElement signatureElement = (XmlElement)sigDocument.Document.SelectSingleNode("//*[@Id='" + counterSignature.Signature.Id + "']");

            counterSigDocument.XadesSignature = new XadesSignedXml(counterSigDocument.Document);
            counterSigDocument.XadesSignature.LoadXml(signatureElement);

            return(counterSigDocument);
        }
Esempio n. 22
0
        public SignatureDocument CounterSign(SignatureDocument sigDocument, SignatureParameters parameters)
        {
            if (parameters.Signer == null)
            {
                throw new Exception("Es necesario un certificado válido para la firma.");
            }
            SignatureDocument.CheckSignatureDocument(sigDocument);
            SignatureDocument signatureDocument = new SignatureDocument();

            signatureDocument.Document = (XmlDocument)sigDocument.Document.Clone();
            signatureDocument.Document.PreserveWhitespace = true;
            XadesSignedXml xadesSignedXml = new XadesSignedXml(signatureDocument.Document);

            xadesSignedXml.Signature.Id     = "xmldsig-" + Guid.NewGuid().ToString();
            xadesSignedXml.SignatureValueId = sigDocument.XadesSignature.Signature.Id + "-sigvalue";
            xadesSignedXml.SigningKey       = parameters.Signer.SigningKey;
            _refContent     = new Reference();
            _refContent.Uri = "#" + sigDocument.XadesSignature.SignatureValueId;
            Reference refContent = _refContent;
            Guid      guid       = Guid.NewGuid();

            refContent.Id    = "Reference-" + guid.ToString();
            _refContent.Type = "http://uri.etsi.org/01903#CountersignedSignature";
            _refContent.AddTransform(new XmlDsigC14NTransform());
            xadesSignedXml.AddReference(_refContent);
            _mimeType = "text/xml";
            _encoding = "UTF-8";
            KeyInfo keyInfo = new KeyInfo();

            keyInfo.Id = "KeyInfoId-" + xadesSignedXml.Signature.Id;
            keyInfo.AddClause(new KeyInfoX509Data(parameters.Signer.Certificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)parameters.Signer.SigningKey));
            xadesSignedXml.KeyInfo = keyInfo;
            Reference reference = new Reference();

            reference.Id  = "ReferenceKeyInfo-" + xadesSignedXml.Signature.Id;
            reference.Uri = "#KeyInfoId-" + xadesSignedXml.Signature.Id;
            xadesSignedXml.AddReference(reference);
            XadesObject xadesObject  = new XadesObject();
            XadesObject xadesObject2 = xadesObject;

            guid            = Guid.NewGuid();
            xadesObject2.Id = "CounterSignatureXadesObject-" + guid.ToString();
            xadesObject.QualifyingProperties.Target = "#" + xadesSignedXml.Signature.Id;
            xadesObject.QualifyingProperties.SignedProperties.Id = "SignedProperties-" + xadesSignedXml.Signature.Id;
            AddSignatureProperties(signatureDocument, xadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties, xadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties, xadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties, parameters);
            xadesSignedXml.AddXadesObject(xadesObject);
            foreach (Reference reference2 in xadesSignedXml.SignedInfo.References)
            {
                reference2.DigestMethod = parameters.DigestMethod.URI;
            }
            xadesSignedXml.SignedInfo.SignatureMethod = parameters.SignatureMethod.URI;
            xadesSignedXml.AddXadesNamespace          = true;
            xadesSignedXml.ComputeSignature();
            signatureDocument.XadesSignature = new XadesSignedXml(signatureDocument.Document);
            signatureDocument.XadesSignature.LoadXml(sigDocument.XadesSignature.GetXml());
            UnsignedProperties unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection.Add(xadesSignedXml);
            signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;
            signatureDocument.UpdateDocument();
            return(signatureDocument);
        }