none
Como Firmar Documento XML con XADES-EPES ? RRS feed

  • Pregunta

  • Hola ...

    Nesecito firmar un documento XML con una firma electronica XADES-EPES y no se como hacerlo?

    Tengo escrito codigo pero solo e podido agregar hasta informacion del certificado.

    Un buen tutorial de ejemplo o indicaciones de como hacerlo seria de gran ayuda ...

    Mi Codigo

    public X509Certificate2Collection ElejirCertificado()
            {
                X509Store store = new X509Store(StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
    
                X509Certificate2Collection certificates = store.Certificates;
                X509Certificate2Collection foundCertificates = certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                X509Certificate2Collection selectedCertificates = X509Certificate2UI.SelectFromCollection(foundCertificates,
                                                                 "Selecciona un certificado.", "Selecciona un certificado de la siguiente lista:", X509SelectionFlag.SingleSelection);
    
                return selectedCertificates;
            }
             public  string  FirmaDigitalCertificada(string path)
    	        {
    	            error = "true";
    	            try
    	            {
    	
    	            X509Certificate2Collection selectedCertificates = new X509Certificate2Collection();
    	            selectedCertificates = ElejirCertificado();
    	            X509Certificate2 certificado = selectedCertificates[0];  
    	            XmlDocument xmlDoc = new XmlDocument();
    	            xmlDoc.PreserveWhitespace = true;
    	            xmlDoc.Load(path);
    	            SignXml2(xmlDoc,certificado);
    	            xmlDoc.Save(path);
    	            }
    	            catch (Exception ex) { error = ex.ToString(); }
    	            return error;
    	        }
    	
    	        public void SignXml2(XmlDocument xmlDoc,  X509Certificate2 certificado)
    	        {
    	
    	            SignedXml signedXml = new SignedXml(xmlDoc);
    	            signedXml.SigningKey = (RSACryptoServiceProvider) certificado.PrivateKey;
    	            Reference reference = new Reference();
    	            reference.Uri = "";
    	
    	            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    	            reference.AddTransform(env);
    	            signedXml.AddReference(reference);
    	            signedXml.Signature.KeyInfo = GetKeyInfoFromCertificate(certificado);
    	            signedXml.ComputeSignature();
    	
    	            XmlElement xmlDigitalSignature = signedXml.GetXml();
    	
    	
    	            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
    	        }
    	
    	        private KeyInfo GetKeyInfoFromCertificate(X509Certificate2 objCertificate)
    	        {
    	            KeyInfo objKeyInfo = new KeyInfo();
    	            objKeyInfo.AddClause(new KeyInfoX509Data(objCertificate));
    	            return objKeyInfo;
            }
    


    EFRAIN MEJIAS C VALENCIA - VENEZUELA

    martes, 19 de septiembre de 2017 22:26

Respuestas

  •     public X509Certificate2 ElegirCertificado()
            {
                X509Store store = new X509Store(StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection certificates = store.Certificates;
                X509Certificate2Collection foundCertificates = certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                X509Certificate2 cert = foundCertificates.OfType<X509Certificate2>().Where(x => x.Subject == "CN=NEOTECNOLOGIAS SOCIEDAD ANONIMA, OU=CPJ, O=PERSONA JURIDICA, C=CR, G=NEOTECNOLOGIAS SOCIEDAD ANONIMA, SN=\"\", SERIALNUMBER=CPJ-3-101-408861").First();
                return cert;
            }
    
            public string PreviaXadesEpes(string path)
            {
                error = "true";
                try
                {
    
                    X509Certificate2 certificado = new X509Certificate2();
                    certificado = ElegirCertificado();
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.PreserveWhitespace = true;
                    
                    xmlDoc.Load(path);
                    xmlDoc=FirmarXadesEPES(xmlDoc, certificado);
                    xmlDoc.Save(path);
                }
                catch (Exception ex) { error = ex.ToString(); }
                return error;
            }
    
    
            private XmlDocument FirmarXadesEPES(XmlDocument xmlDoc, X509Certificate2 certificate)
            {
               
                XadesSignedXml signedXml = new XadesSignedXml(xmlDoc);
                signedXml.Signature.Id = "SignatureId";
                signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
                signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
    
                string URI = "http://uri.etsi.org/01903/v1.3.2#";
                XmlElement qualifyingPropertiesRoot = xmlDoc.CreateElement("xades", "QualifyingProperties", URI);
                qualifyingPropertiesRoot.SetAttribute("Target", "#SignatureId",URI);
    
                XmlElement signaturePropertiesRoot = xmlDoc.CreateElement("xades", "SignedProperties", URI);
                signaturePropertiesRoot.SetAttribute("Id", "SignedPropertiesId",URI);
    
                XmlElement SignedSignatureProperties = xmlDoc.CreateElement("xades", "SignedSignatureProperties", URI);
    
                XmlElement timestamp = xmlDoc.CreateElement("xades", "SigningTime", URI);
                timestamp.InnerText = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"); //2011-09-05T09:11:24.268Z
                SignedSignatureProperties.AppendChild(timestamp);
    
                XmlElement SigningCertificate = xmlDoc.CreateElement("xades", "SigningCertificate", URI);
                XmlElement Cert = xmlDoc.CreateElement("xades", "Cert", URI);
                XmlElement CertDigest = xmlDoc.CreateElement("xades", "CertDigest", URI);
                SHA1 cryptoServiceProvider = new SHA1CryptoServiceProvider();
                byte[] sha1 = cryptoServiceProvider.ComputeHash(certificate.RawData);
    
                XmlElement DigestMethod = xmlDoc.CreateElement("ds", "DigestMethod", URI);
    
                DigestMethod.SetAttribute("Algorithm", SignedXml.XmlDsigSHA1Url);
                XmlElement DigestValue = xmlDoc.CreateElement("ds", "DigestValue", URI);
                DigestValue.InnerText = Convert.ToBase64String(sha1);
                CertDigest.AppendChild(DigestMethod);
                CertDigest.AppendChild(DigestValue);
                Cert.AppendChild(CertDigest);
    
                XmlElement IssuerSerial = xmlDoc.CreateElement("xades", "IssuerSerial", URI);
                XmlElement X509IssuerName = xmlDoc.CreateElement("ds", "X509IssuerName", "http://www.w3.org/2000/09/xmldsig#");
                X509IssuerName.InnerText = certificate.IssuerName.Name;
                XmlElement X509SerialNumber = xmlDoc.CreateElement("ds", "X509SerialNumber", "http://www.w3.org/2000/09/xmldsig#");
                X509SerialNumber.InnerText = certificate.SerialNumber;
                IssuerSerial.AppendChild(X509IssuerName);
                IssuerSerial.AppendChild(X509SerialNumber);
                Cert.AppendChild(IssuerSerial);
    
                SigningCertificate.AppendChild(Cert);
                SignedSignatureProperties.AppendChild(SigningCertificate);
    
                signaturePropertiesRoot.AppendChild(SignedSignatureProperties);
                qualifyingPropertiesRoot.AppendChild(signaturePropertiesRoot);
    
                // /////////////////////////////////
                XmlElement SignaturePolicyIdentifier = xmlDoc.CreateElement("xades", "SignaturePolicyIdentifier", URI);
                SignedSignatureProperties.AppendChild(SignaturePolicyIdentifier);
    
                XmlElement SignaturePolicyId = xmlDoc.CreateElement("xades", "SignaturePolicyId", URI);
                SignaturePolicyIdentifier.AppendChild(SignaturePolicyId);
    
                XmlElement SigPolicyId = xmlDoc.CreateElement("xades", "SigPolicyId", URI);
                SignaturePolicyId.AppendChild(SigPolicyId);
    
                XmlElement Identifier = xmlDoc.CreateElement("xades", "Identifier", URI);
                Identifier.InnerText = "https://tribunet.hacienda.go.cr/docs/esquemas/2016/v4.1/Resolucion_Comprobantes_Electronicos_DGT-R-48-2016.pdf";
                SigPolicyId.AppendChild(Identifier);
    
                XmlElement SigPolicyHash = xmlDoc.CreateElement("xades", "SigPolicyHash", URI);
                SignaturePolicyId.AppendChild(SigPolicyHash);
    
                DigestMethod = xmlDoc.CreateElement("ds", "DigestMethod", URI);
                DigestMethod.SetAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#sha256");
                DigestValue = xmlDoc.CreateElement("ds", "DigestValue", URI);
                byte[] shaCertificate = { 0xf1, 0x48, 0x03, 0x50, 0x5c, 0x33, 0x64, 0x29, 0x07, 0x84, 0x43, 0xca, 0x79, 0x6e, 0x59, 0xcc, 0xac, 0xf5, 0x85, 0x4c };
                DigestValue.InnerText = Convert.ToBase64String(shaCertificate);
                SigPolicyHash.AppendChild(DigestMethod);
                SigPolicyHash.AppendChild(DigestValue);
    
                XmlElement SignedDataObjectProperties = xmlDoc.CreateElement("xades", "SignedDataObjectProperties", URI);
                XmlElement DataObjectFormat = xmlDoc.CreateElement("xades", "DataObjectFormat", URI);
                DataObjectFormat.SetAttribute("ObjectReference", "#r-id-1");
                signaturePropertiesRoot.AppendChild(SignedDataObjectProperties);
                SignedDataObjectProperties.AppendChild(DataObjectFormat);
                XmlElement MimeType = xmlDoc.CreateElement("xades", "MimeType", URI);
                MimeType.InnerText = "application/octet-stream";
                DataObjectFormat.AppendChild(MimeType);
                // /////////////////////////////////////////////////////////////
    
                DataObject dataObject = new DataObject
                {
                    Data = qualifyingPropertiesRoot.SelectNodes("."),
                };
              
                signedXml.AddObject(dataObject);
                signedXml.SigningKey = certificate.PrivateKey;
    
                KeyInfo keyInfo = new KeyInfo();
                KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot);
                keyInfo.AddClause(keyInfoX509Data);
                signedXml.KeyInfo = keyInfo;
    
                //Reference 1
                Reference reference2 = new Reference();
                reference2.Id = "R1";
                reference2.Type = "http://uri.etsi.org/01903#SignedProperties";
                reference2.Uri = "";
                XmlDsigXPathTransform XPathTransform = CreateXPathTransform("ValorPath",xmlDoc);
                reference2.AddTransform(XPathTransform);
                reference2.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                reference2.AddTransform(new XmlDsigExcC14NTransform());
                signedXml.AddReference(reference2);
    
               //Reference 2
                reference2 = new Reference();
               // reference2.Id = "R2";
                reference2.Type = "http://uri.etsi.org/01903#SignedProperties";
                reference2.Uri = "";
                // reference2.AddTransform(new XmlDsigExcC14NTransform());
                XPathTransform = CreateXPathTransform("ValorPath",xmlDoc );
               // reference2.AddTransform(XPathTransform);
                reference2.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                reference2.AddTransform(new XmlDsigExcC14NTransform());
                signedXml.AddReference(reference2); 
    
                signedXml.ComputeSignature();
                XmlElement xmlDigitalSignature = signedXml.GetXml();
                xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
    
                bool checkSign = signedXml.CheckSignature();
                //return xmlDoc.OuterXml;
                return xmlDoc;
    
            }
            private static XmlDsigXPathTransform CreateXPathTransform(string XPathString,XmlDocument doc)
            {
                //XmlDocument doc = new XmlDocument();
                XmlElement xPathElem = doc.CreateElement("XPath");
                xPathElem.InnerText = XPathString;
                XmlDsigXPathTransform xForm = new XmlDsigXPathTransform();
                xForm.LoadInnerXml(xPathElem.SelectNodes("."));
                return xForm;
            }
    


    EFRAIN MEJIAS C VALENCIA - VENEZUELA

    viernes, 29 de septiembre de 2017 8:44

Todas las respuestas

  •     public X509Certificate2 ElegirCertificado()
            {
                X509Store store = new X509Store(StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection certificates = store.Certificates;
                X509Certificate2Collection foundCertificates = certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                X509Certificate2 cert = foundCertificates.OfType<X509Certificate2>().Where(x => x.Subject == "CN=NEOTECNOLOGIAS SOCIEDAD ANONIMA, OU=CPJ, O=PERSONA JURIDICA, C=CR, G=NEOTECNOLOGIAS SOCIEDAD ANONIMA, SN=\"\", SERIALNUMBER=CPJ-3-101-408861").First();
                return cert;
            }
    
            public string PreviaXadesEpes(string path)
            {
                error = "true";
                try
                {
    
                    X509Certificate2 certificado = new X509Certificate2();
                    certificado = ElegirCertificado();
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.PreserveWhitespace = true;
                    
                    xmlDoc.Load(path);
                    xmlDoc=FirmarXadesEPES(xmlDoc, certificado);
                    xmlDoc.Save(path);
                }
                catch (Exception ex) { error = ex.ToString(); }
                return error;
            }
    
    
            private XmlDocument FirmarXadesEPES(XmlDocument xmlDoc, X509Certificate2 certificate)
            {
               
                XadesSignedXml signedXml = new XadesSignedXml(xmlDoc);
                signedXml.Signature.Id = "SignatureId";
                signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
                signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
    
                string URI = "http://uri.etsi.org/01903/v1.3.2#";
                XmlElement qualifyingPropertiesRoot = xmlDoc.CreateElement("xades", "QualifyingProperties", URI);
                qualifyingPropertiesRoot.SetAttribute("Target", "#SignatureId",URI);
    
                XmlElement signaturePropertiesRoot = xmlDoc.CreateElement("xades", "SignedProperties", URI);
                signaturePropertiesRoot.SetAttribute("Id", "SignedPropertiesId",URI);
    
                XmlElement SignedSignatureProperties = xmlDoc.CreateElement("xades", "SignedSignatureProperties", URI);
    
                XmlElement timestamp = xmlDoc.CreateElement("xades", "SigningTime", URI);
                timestamp.InnerText = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"); //2011-09-05T09:11:24.268Z
                SignedSignatureProperties.AppendChild(timestamp);
    
                XmlElement SigningCertificate = xmlDoc.CreateElement("xades", "SigningCertificate", URI);
                XmlElement Cert = xmlDoc.CreateElement("xades", "Cert", URI);
                XmlElement CertDigest = xmlDoc.CreateElement("xades", "CertDigest", URI);
                SHA1 cryptoServiceProvider = new SHA1CryptoServiceProvider();
                byte[] sha1 = cryptoServiceProvider.ComputeHash(certificate.RawData);
    
                XmlElement DigestMethod = xmlDoc.CreateElement("ds", "DigestMethod", URI);
    
                DigestMethod.SetAttribute("Algorithm", SignedXml.XmlDsigSHA1Url);
                XmlElement DigestValue = xmlDoc.CreateElement("ds", "DigestValue", URI);
                DigestValue.InnerText = Convert.ToBase64String(sha1);
                CertDigest.AppendChild(DigestMethod);
                CertDigest.AppendChild(DigestValue);
                Cert.AppendChild(CertDigest);
    
                XmlElement IssuerSerial = xmlDoc.CreateElement("xades", "IssuerSerial", URI);
                XmlElement X509IssuerName = xmlDoc.CreateElement("ds", "X509IssuerName", "http://www.w3.org/2000/09/xmldsig#");
                X509IssuerName.InnerText = certificate.IssuerName.Name;
                XmlElement X509SerialNumber = xmlDoc.CreateElement("ds", "X509SerialNumber", "http://www.w3.org/2000/09/xmldsig#");
                X509SerialNumber.InnerText = certificate.SerialNumber;
                IssuerSerial.AppendChild(X509IssuerName);
                IssuerSerial.AppendChild(X509SerialNumber);
                Cert.AppendChild(IssuerSerial);
    
                SigningCertificate.AppendChild(Cert);
                SignedSignatureProperties.AppendChild(SigningCertificate);
    
                signaturePropertiesRoot.AppendChild(SignedSignatureProperties);
                qualifyingPropertiesRoot.AppendChild(signaturePropertiesRoot);
    
                // /////////////////////////////////
                XmlElement SignaturePolicyIdentifier = xmlDoc.CreateElement("xades", "SignaturePolicyIdentifier", URI);
                SignedSignatureProperties.AppendChild(SignaturePolicyIdentifier);
    
                XmlElement SignaturePolicyId = xmlDoc.CreateElement("xades", "SignaturePolicyId", URI);
                SignaturePolicyIdentifier.AppendChild(SignaturePolicyId);
    
                XmlElement SigPolicyId = xmlDoc.CreateElement("xades", "SigPolicyId", URI);
                SignaturePolicyId.AppendChild(SigPolicyId);
    
                XmlElement Identifier = xmlDoc.CreateElement("xades", "Identifier", URI);
                Identifier.InnerText = "https://tribunet.hacienda.go.cr/docs/esquemas/2016/v4.1/Resolucion_Comprobantes_Electronicos_DGT-R-48-2016.pdf";
                SigPolicyId.AppendChild(Identifier);
    
                XmlElement SigPolicyHash = xmlDoc.CreateElement("xades", "SigPolicyHash", URI);
                SignaturePolicyId.AppendChild(SigPolicyHash);
    
                DigestMethod = xmlDoc.CreateElement("ds", "DigestMethod", URI);
                DigestMethod.SetAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#sha256");
                DigestValue = xmlDoc.CreateElement("ds", "DigestValue", URI);
                byte[] shaCertificate = { 0xf1, 0x48, 0x03, 0x50, 0x5c, 0x33, 0x64, 0x29, 0x07, 0x84, 0x43, 0xca, 0x79, 0x6e, 0x59, 0xcc, 0xac, 0xf5, 0x85, 0x4c };
                DigestValue.InnerText = Convert.ToBase64String(shaCertificate);
                SigPolicyHash.AppendChild(DigestMethod);
                SigPolicyHash.AppendChild(DigestValue);
    
                XmlElement SignedDataObjectProperties = xmlDoc.CreateElement("xades", "SignedDataObjectProperties", URI);
                XmlElement DataObjectFormat = xmlDoc.CreateElement("xades", "DataObjectFormat", URI);
                DataObjectFormat.SetAttribute("ObjectReference", "#r-id-1");
                signaturePropertiesRoot.AppendChild(SignedDataObjectProperties);
                SignedDataObjectProperties.AppendChild(DataObjectFormat);
                XmlElement MimeType = xmlDoc.CreateElement("xades", "MimeType", URI);
                MimeType.InnerText = "application/octet-stream";
                DataObjectFormat.AppendChild(MimeType);
                // /////////////////////////////////////////////////////////////
    
                DataObject dataObject = new DataObject
                {
                    Data = qualifyingPropertiesRoot.SelectNodes("."),
                };
              
                signedXml.AddObject(dataObject);
                signedXml.SigningKey = certificate.PrivateKey;
    
                KeyInfo keyInfo = new KeyInfo();
                KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot);
                keyInfo.AddClause(keyInfoX509Data);
                signedXml.KeyInfo = keyInfo;
    
                //Reference 1
                Reference reference2 = new Reference();
                reference2.Id = "R1";
                reference2.Type = "http://uri.etsi.org/01903#SignedProperties";
                reference2.Uri = "";
                XmlDsigXPathTransform XPathTransform = CreateXPathTransform("ValorPath",xmlDoc);
                reference2.AddTransform(XPathTransform);
                reference2.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                reference2.AddTransform(new XmlDsigExcC14NTransform());
                signedXml.AddReference(reference2);
    
               //Reference 2
                reference2 = new Reference();
               // reference2.Id = "R2";
                reference2.Type = "http://uri.etsi.org/01903#SignedProperties";
                reference2.Uri = "";
                // reference2.AddTransform(new XmlDsigExcC14NTransform());
                XPathTransform = CreateXPathTransform("ValorPath",xmlDoc );
               // reference2.AddTransform(XPathTransform);
                reference2.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                reference2.AddTransform(new XmlDsigExcC14NTransform());
                signedXml.AddReference(reference2); 
    
                signedXml.ComputeSignature();
                XmlElement xmlDigitalSignature = signedXml.GetXml();
                xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
    
                bool checkSign = signedXml.CheckSignature();
                //return xmlDoc.OuterXml;
                return xmlDoc;
    
            }
            private static XmlDsigXPathTransform CreateXPathTransform(string XPathString,XmlDocument doc)
            {
                //XmlDocument doc = new XmlDocument();
                XmlElement xPathElem = doc.CreateElement("XPath");
                xPathElem.InnerText = XPathString;
                XmlDsigXPathTransform xForm = new XmlDsigXPathTransform();
                xForm.LoadInnerXml(xPathElem.SelectNodes("."));
                return xForm;
            }
    


    EFRAIN MEJIAS C VALENCIA - VENEZUELA

    viernes, 29 de septiembre de 2017 8:44
  • Hola, 

    El codigo que usa la clase XadesSignedXml, pudieras orientarme sobre donde puedo encontrarla?

    Saludos

    lunes, 30 de octubre de 2017 18:30
  • sera que exista alguna clase para firmar pero con PHP?
    jueves, 23 de noviembre de 2017 4:44
  • Hola, adonde está XadesSignedXml?

    ------------------------ Rol Developer.

    domingo, 3 de diciembre de 2017 3:15
  • Saludos, alguien ha logrado resolver el asunto con la clase XadesSignedXML?, yo la encontré en https://github.com/Caliper/Xades/blob/master/Source/Library/XadesSignedXml.cs, pero no logro resolver el problema con las referencias y gran cantidad de errores que aparecen al agregarla al proyecto. Si alguien logra resolver algo puede por favor postear por aca.
    lunes, 8 de enero de 2018 13:23
  • Alli publique la librería que hace el firmado para costa rica.

    https://groups.google.com/forum/#!topic/publicesvfoxpro/Jwg_5IIEh3Q

    Saludos

    lunes, 22 de enero de 2018 2:57
  • Pudiste saber algo?
    viernes, 2 de febrero de 2018 21:47
  •     public X509Certificate2 ElegirCertificado()
            {
                X509Store store = new X509Store(StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection certificates = store.Certificates;
                X509Certificate2Collection foundCertificates = certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                X509Certificate2 cert = foundCertificates.OfType<X509Certificate2>().Where(x => x.Subject == "CN=NEOTECNOLOGIAS SOCIEDAD ANONIMA, OU=CPJ, O=PERSONA JURIDICA, C=CR, G=NEOTECNOLOGIAS SOCIEDAD ANONIMA, SN=\"\", SERIALNUMBER=CPJ-3-101-408861").First();
                return cert;
            }
    
            public string PreviaXadesEpes(string path)
            {
                error = "true";
                try
                {
    
                    X509Certificate2 certificado = new X509Certificate2();
                    certificado = ElegirCertificado();
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.PreserveWhitespace = true;
                    
                    xmlDoc.Load(path);
                    xmlDoc=FirmarXadesEPES(xmlDoc, certificado);
                    xmlDoc.Save(path);
                }
                catch (Exception ex) { error = ex.ToString(); }
                return error;
            }
    
    
            private XmlDocument FirmarXadesEPES(XmlDocument xmlDoc, X509Certificate2 certificate)
            {
               
                XadesSignedXml signedXml = new XadesSignedXml(xmlDoc);
                signedXml.Signature.Id = "SignatureId";
                signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
                signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
    
                string URI = "http://uri.etsi.org/01903/v1.3.2#";
                XmlElement qualifyingPropertiesRoot = xmlDoc.CreateElement("xades", "QualifyingProperties", URI);
                qualifyingPropertiesRoot.SetAttribute("Target", "#SignatureId",URI);
    
                XmlElement signaturePropertiesRoot = xmlDoc.CreateElement("xades", "SignedProperties", URI);
                signaturePropertiesRoot.SetAttribute("Id", "SignedPropertiesId",URI);
    
                XmlElement SignedSignatureProperties = xmlDoc.CreateElement("xades", "SignedSignatureProperties", URI);
    
                XmlElement timestamp = xmlDoc.CreateElement("xades", "SigningTime", URI);
                timestamp.InnerText = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"); //2011-09-05T09:11:24.268Z
                SignedSignatureProperties.AppendChild(timestamp);
    
                XmlElement SigningCertificate = xmlDoc.CreateElement("xades", "SigningCertificate", URI);
                XmlElement Cert = xmlDoc.CreateElement("xades", "Cert", URI);
                XmlElement CertDigest = xmlDoc.CreateElement("xades", "CertDigest", URI);
                SHA1 cryptoServiceProvider = new SHA1CryptoServiceProvider();
                byte[] sha1 = cryptoServiceProvider.ComputeHash(certificate.RawData);
    
                XmlElement DigestMethod = xmlDoc.CreateElement("ds", "DigestMethod", URI);
    
                DigestMethod.SetAttribute("Algorithm", SignedXml.XmlDsigSHA1Url);
                XmlElement DigestValue = xmlDoc.CreateElement("ds", "DigestValue", URI);
                DigestValue.InnerText = Convert.ToBase64String(sha1);
                CertDigest.AppendChild(DigestMethod);
                CertDigest.AppendChild(DigestValue);
                Cert.AppendChild(CertDigest);
    
                XmlElement IssuerSerial = xmlDoc.CreateElement("xades", "IssuerSerial", URI);
                XmlElement X509IssuerName = xmlDoc.CreateElement("ds", "X509IssuerName", "http://www.w3.org/2000/09/xmldsig#");
                X509IssuerName.InnerText = certificate.IssuerName.Name;
                XmlElement X509SerialNumber = xmlDoc.CreateElement("ds", "X509SerialNumber", "http://www.w3.org/2000/09/xmldsig#");
                X509SerialNumber.InnerText = certificate.SerialNumber;
                IssuerSerial.AppendChild(X509IssuerName);
                IssuerSerial.AppendChild(X509SerialNumber);
                Cert.AppendChild(IssuerSerial);
    
                SigningCertificate.AppendChild(Cert);
                SignedSignatureProperties.AppendChild(SigningCertificate);
    
                signaturePropertiesRoot.AppendChild(SignedSignatureProperties);
                qualifyingPropertiesRoot.AppendChild(signaturePropertiesRoot);
    
                // /////////////////////////////////
                XmlElement SignaturePolicyIdentifier = xmlDoc.CreateElement("xades", "SignaturePolicyIdentifier", URI);
                SignedSignatureProperties.AppendChild(SignaturePolicyIdentifier);
    
                XmlElement SignaturePolicyId = xmlDoc.CreateElement("xades", "SignaturePolicyId", URI);
                SignaturePolicyIdentifier.AppendChild(SignaturePolicyId);
    
                XmlElement SigPolicyId = xmlDoc.CreateElement("xades", "SigPolicyId", URI);
                SignaturePolicyId.AppendChild(SigPolicyId);
    
                XmlElement Identifier = xmlDoc.CreateElement("xades", "Identifier", URI);
                Identifier.InnerText = "https://tribunet.hacienda.go.cr/docs/esquemas/2016/v4.1/Resolucion_Comprobantes_Electronicos_DGT-R-48-2016.pdf";
                SigPolicyId.AppendChild(Identifier);
    
                XmlElement SigPolicyHash = xmlDoc.CreateElement("xades", "SigPolicyHash", URI);
                SignaturePolicyId.AppendChild(SigPolicyHash);
    
                DigestMethod = xmlDoc.CreateElement("ds", "DigestMethod", URI);
                DigestMethod.SetAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#sha256");
                DigestValue = xmlDoc.CreateElement("ds", "DigestValue", URI);
                byte[] shaCertificate = { 0xf1, 0x48, 0x03, 0x50, 0x5c, 0x33, 0x64, 0x29, 0x07, 0x84, 0x43, 0xca, 0x79, 0x6e, 0x59, 0xcc, 0xac, 0xf5, 0x85, 0x4c };
                DigestValue.InnerText = Convert.ToBase64String(shaCertificate);
                SigPolicyHash.AppendChild(DigestMethod);
                SigPolicyHash.AppendChild(DigestValue);
    
                XmlElement SignedDataObjectProperties = xmlDoc.CreateElement("xades", "SignedDataObjectProperties", URI);
                XmlElement DataObjectFormat = xmlDoc.CreateElement("xades", "DataObjectFormat", URI);
                DataObjectFormat.SetAttribute("ObjectReference", "#r-id-1");
                signaturePropertiesRoot.AppendChild(SignedDataObjectProperties);
                SignedDataObjectProperties.AppendChild(DataObjectFormat);
                XmlElement MimeType = xmlDoc.CreateElement("xades", "MimeType", URI);
                MimeType.InnerText = "application/octet-stream";
                DataObjectFormat.AppendChild(MimeType);
                // /////////////////////////////////////////////////////////////
    
                DataObject dataObject = new DataObject
                {
                    Data = qualifyingPropertiesRoot.SelectNodes("."),
                };
              
                signedXml.AddObject(dataObject);
                signedXml.SigningKey = certificate.PrivateKey;
    
                KeyInfo keyInfo = new KeyInfo();
                KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot);
                keyInfo.AddClause(keyInfoX509Data);
                signedXml.KeyInfo = keyInfo;
    
                //Reference 1
                Reference reference2 = new Reference();
                reference2.Id = "R1";
                reference2.Type = "http://uri.etsi.org/01903#SignedProperties";
                reference2.Uri = "";
                XmlDsigXPathTransform XPathTransform = CreateXPathTransform("ValorPath",xmlDoc);
                reference2.AddTransform(XPathTransform);
                reference2.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                reference2.AddTransform(new XmlDsigExcC14NTransform());
                signedXml.AddReference(reference2);
    
               //Reference 2
                reference2 = new Reference();
               // reference2.Id = "R2";
                reference2.Type = "http://uri.etsi.org/01903#SignedProperties";
                reference2.Uri = "";
                // reference2.AddTransform(new XmlDsigExcC14NTransform());
                XPathTransform = CreateXPathTransform("ValorPath",xmlDoc );
               // reference2.AddTransform(XPathTransform);
                reference2.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                reference2.AddTransform(new XmlDsigExcC14NTransform());
                signedXml.AddReference(reference2); 
    
                signedXml.ComputeSignature();
                XmlElement xmlDigitalSignature = signedXml.GetXml();
                xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
    
                bool checkSign = signedXml.CheckSignature();
                //return xmlDoc.OuterXml;
                return xmlDoc;
    
            }
            private static XmlDsigXPathTransform CreateXPathTransform(string XPathString,XmlDocument doc)
            {
                //XmlDocument doc = new XmlDocument();
                XmlElement xPathElem = doc.CreateElement("XPath");
                xPathElem.InnerText = XPathString;
                XmlDsigXPathTransform xForm = new XmlDsigXPathTransform();
                xForm.LoadInnerXml(xPathElem.SelectNodes("."));
                return xForm;
            }


    EFRAIN MEJIAS C VALENCIA - VENEZUELA

    Saludos estimado, no se si Ud completo todo, ocupo una referencia de como hacer el metodo descrito
    viernes, 2 de febrero de 2018 21:49
  • Hola Cristian Sancho... Puedo firmar el documento pero aun hacienda no lo acepta como valido, puedes explicarme mejor lo que nesecitas...

    EFRAIN MEJIAS C VALENCIA - VENEZUELA

    domingo, 4 de febrero de 2018 20:01
  • Soy programador freelance, ya la tengo desarrollada en Javascript y php  si es de su interes puede escribir a alexander2714@gmail.com

    viernes, 6 de abril de 2018 21:24
  • Mi contribución con los hermanos de Costa Rica en PHP puro.

    https://github.com/CRLibre/API_Hacienda/blob/master/api/contrib/signXML/Firmadohaciendacr.php

    sábado, 7 de abril de 2018 19:48
  • Buenas jose como logro contactarte por otro medio que no sea este? mi correo lurobaca @ g mail.com para hacerte una consulta sobre esa clase
    lunes, 30 de abril de 2018 18:01
  • Excelente. ya probe el DLL y funciona a la perfección 

    Queria preguntarte si tienes el fuente.. quiero hacer una implementacion en VB.NET

    Gracias

    • Propuesto como respuesta Gary Tambo viernes, 10 de agosto de 2018 7:51
    • Votado como útil Gary Tambo viernes, 10 de agosto de 2018 7:51
    miércoles, 16 de mayo de 2018 2:51
  • Christopher,

    una consulta con que dll probastes 

    viernes, 10 de agosto de 2018 7:45
  • Excelente. ya probe el DLL y funciona a la perfección 

    Queria preguntarte si tienes el fuente.. quiero hacer una implementacion en VB.NET

    Gracias

    Christopher, una consulta con que dll probastes.

    viernes, 10 de agosto de 2018 7:50
  • Hola Cristian Sancho... Puedo firmar el documento pero aun hacienda no lo acepta como valido, puedes explicarme mejor lo que nesecitas...

    EFRAIN MEJIAS C VALENCIA - VENEZUELA

    una consulta, pudistes resolver el problema del firmado
    viernes, 10 de agosto de 2018 7:55
  • si ya pude firmar :::

    EFRAIN MEJIAS C VALENCIA - VENEZUELA

    sábado, 11 de agosto de 2018 22:12
  • A los interesados Componente DLL para FE: http://edwinjuarezdeveloper.blogspot.com/2018/08/facturacion-electronica-costa-rica.html
    viernes, 28 de diciembre de 2018 15:16
  • nesecito ─► necesito

    solo e podido ─► solo he podido

    lunes, 11 de febrero de 2019 22:17
  • disculpa podrias ayudarme estoy tratando de usar tu codigo para una prueba de firmar un documento xml, pero me da el error al generar de algoritmo especificado no es valido. lo que hice fue copiar tu codigo y probarlo. O si tendras alguna documentacion que pueda utilizar de antemano muchas gracias.
    martes, 28 de mayo de 2019 18:30