5

Desarrollo una aplicación donde firmo un documento XML digitalmente, pero no sé cómo hacer para agregar el Prefijo (xs) a los nodos que genera la firma.

<xs:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> 

Mi Código:

 private string  FirmaXadesEPES(XmlDocument xmlDoc, X509Certificate2 certificate,string path)
    {
        error = string.Empty;
        idFirma = IdSignature();
        SignedXml signedXml = new SignedXml(xmlDoc);
        string URI = "http://uri.etsi.org/01903/v1.3.2#";
        try
        {
            signedXml.Signature.Id = "Id-" + idFirma;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            signedXml.SigningKey = certificate.PrivateKey;
            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot);
            keyInfo.AddClause(keyInfoX509Data);
            signedXml.KeyInfo = keyInfo;
            //Reference 1
            Reference reference = new Reference();
            reference.Id = "r-id-" + idFirma;
            reference.Type = "";
            reference.Uri = "";
            XmlDsigXPathTransform XPathTransform = CreateXPathTransform("//. | //@* | //namespace::*", xmlDoc);
            reference.AddTransform(XPathTransform);
            reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(reference);
            //Reference 2
            Reference reference2 = new Reference();
            reference2.Type = "http://uri.etsi.org/01903#SignedProperties";
            reference2.Uri = "";
            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();

        } catch (Exception ex) { error = ex.ToString(); }

        xmlDoc.Save(path);
        return error;
    }

Firma Generada:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#" Id="Id-37d3fd17-b0f9-48f0-add9-75a52bb9e83c-59880">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
    <Reference Id="r-id-37d3fd17-b0f9-48f0-add9-75a52bb9e83c-59880" URI="">
      <Transforms>
        <Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
          <XPath>//. | //@* | //namespace::*</XPath>
        </Transform>
        <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
      </Transforms>
      <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
      <DigestValue>HiOIkatoMGOfHDeUaCFmeWGrYOhHtkItSfRwvc/z5Vo=</DigestValue>
    </Reference>
    <Reference URI="" Type="http://uri.etsi.org/01903#SignedProperties">
      <Transforms>
        <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
      </Transforms>
      <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
      <DigestValue>HiOIkatoMGOfHDeUaCFmeWGrYOhHtkItSfRwvc/z5Vo=</DigestValue>
    </Reference>
  </SignedInfo>
  <SignatureValue>P3ElvXAHH1gXbcmiYCyl2OERHeeKOwOER7MFcBHRaYc47rhPmJQl99kiCo4kvXTEEonRVcNYe6jLSFy8bmXxlrLmQ4O5ju/7IOtZqPIcJpOvGQjKlCFw/o3lczynSuSR1sIGWiKe33wV4rahfc5N5dO8PVMSTAz2GgCrDFrVSAg7i4VmAyWoS45qrtgLwh+tIaX8Oc6zSwsiMbJUZ+k9GYFiO9FERoB5ww3AJenylL8wDo4wmGvaBuBjDU0+mgZyeutkgHA7Xge3MQ0QuuGm4FRtYR4itqGq1rnilHmhOxtvqyeNdipg5WKKhuQM55m2eQbdjVFPzC9nJTpIoW7X5g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ERFIEhBQ0lFTkRBIC0gU0FOREJPWIIEWKUQdDAdBgNVHQ4EFgQUrChF+C+dSF8sHwCQ6zLFowdTgOEwCwYDVR0PBAQDAgGGMA0GCSqGSIb3DQEBDQUAA4ICAQBrSW828HiLsXmxShXL29gmmOQ0LPwTlqQuD5HRD6ay2SjqxixIdLiImqddfRzSt6SXU0RsQzgEnX2/iREfIdDz0jAH2qgDNu/Z5dCqRGQ3ap/czvrpGMdC3ungvU5keRRRNRTkhhnwsRKo/Kz4FoBrPitJ0INxqy0zLLRo4/AKVQOUa2N0GmhV5t5l9RbJlnlhaEvlbI/swqRlYahgIDooKh2IYhhpX0G0YQsOZ4ZCSlfAomJUnvryVonziOvdHSDFCuVzqokg/EUMJk7RMrZ1M9OTc/6t7Io3n9Se5OWgH1H8k5bcwdG3xeJTRDtEyJQahyk6fXzo3YikhhqubngzNGzrD65t4H/g58stYUJf5mNPoJdgJIjPzbF00l2hkjNneB+gGnWRCfQnFOYDU5WmCjrepX+RIG1BwEuVa113lc3OFPBcNFOY5z2BSJKGQanAJPsFLLGU4foXXdv+cVAN7gKvXFl9kKGShdI07Dfmz2gY0f+L7795ZB8SAhyXgCd/jZH3Fz4ciLrxXnV4/hg7jjZ5dBwH7mFH/6ZD44sMtCC1SVL1mPvWagXlc+DWADdTaHfJCWITWCcQGQAgXeoqqVe7sCwGen07sKvhnt+VOusTmGhg2eOp/wZ37R4ILeGsvhSOB5kHRZnGqUrfPXlkFMgmgbsDSU5frxz49FtvYA==</X509Certificate>
    </X509Data>
  </KeyInfo>
</Signature>

3 respuestas 3

1

Agregue este Metodo AgregarPrefijo(XmlNodet n) el cual recibe como parametro el nodo de la firma :

private void AgregaPrefijo(XmlNode n)
    {
            string[] nodos = { ELEMENTOS A LOS QUE QUIERO AGREGARLE EL PRFIJO};
            int reference = 0;
            try
            {
                foreach (XmlElement item in n.Cast<XmlNode>().Where(e => e.NodeType == XmlNodeType.Element))
                {
                    string nombre = item.Name;
                    if (nodos.Contains (nombre))
                    {
                        item.Prefix = "ds";
                        if (item.HasChildNodes)
                        {
                            AgregaPrefijo(item);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.ToString();
            }
        }

 private string  FirmaXadesEPES(XmlDocument xmlDoc, X509Certificate2 certificate,string path)
    {
        error = string.Empty;
        idFirma = IdSignature();
        SignedXml signedXml = new SignedXml(xmlDoc);
        string URI = "http://uri.etsi.org/01903/v1.3.2#";
        try
        {
            signedXml.Signature.Id = "Id-" + idFirma;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            signedXml.SigningKey = certificate.PrivateKey;
            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot);
            keyInfo.AddClause(keyInfoX509Data);
            signedXml.KeyInfo = keyInfo;
            //Reference 1
            Reference reference = new Reference();
            reference.Id = "r-id-" + idFirma;
            reference.Type = "";
            reference.Uri = "";
            XmlDsigXPathTransform XPathTransform = CreateXPathTransform("//. | //@* | //namespace::*", xmlDoc);
            reference.AddTransform(XPathTransform);
            reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(reference);
            //Reference 2
            Reference reference2 = new Reference();
            reference2.Type = "http://uri.etsi.org/01903#SignedProperties";
            reference2.Uri = "";
            reference2.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
            reference2.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(reference2);
            signedXml.ComputeSignature();

               XmlElement xmlDigitalSignature = signedXml.GetXml();
            xmlDigitalSignature.Prefix = "ds";
            **AgregaPrefijo(xmlDigitalSignature);**
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
            bool checkSign = signedXml.CheckSignature();

        } catch (Exception ex) { error = ex.ToString(); }

        xmlDoc.Save(path);
        return error;
    }

y antes de guardar el documento en el metodo FirmaXadesEPES() agrego estas lineas para Invocarlo

 xmlDigitalSignature.Prefix = "ds";
        AgregaPrefijo(xmlDigitalSignature);
0

cuando te refieres a que le coloques un prefijo a los nodos es crear un archivo de esquema.

<?xml version="1.0" encoding="utf-8"?>
  <xs:schema attributeFormDefault="unqualified" 
  elementFormDefault="qualified" 
 targetNamespace="http://www.w3.org/2000/09/xmldsig#" 
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element name="Signature">
  <xs:complexType>
  <xs:sequence>
    <xs:element name="SignedInfo">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="CanonicalizationMethod">
            <xs:complexType>
              <xs:attribute name="Algorithm" type="xs:string" use="required" 
     />
            </xs:complexType>
          </xs:element>
          <xs:element name="SignatureMethod">
            <xs:complexType>
              <xs:attribute name="Algorithm" type="xs:string" use="required" 
    />
            </xs:complexType>
          </xs:element>
          <xs:element maxOccurs="unbounded" name="Reference">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="Transforms">
                  <xs:complexType>
                    <xs:sequence>
                      <xs:element maxOccurs="unbounded" name="Transform">
                        <xs:complexType>
                          <xs:sequence minOccurs="0">
                            <xs:element name="XPath" type="xs:string" />
                          </xs:sequence>
                          <xs:attribute name="Algorithm" type="xs:string" 
        use="required" />
                        </xs:complexType>
                      </xs:element>
                    </xs:sequence>
                  </xs:complexType>
                </xs:element>
                <xs:element name="DigestMethod">
                  <xs:complexType>
                    <xs:attribute name="Algorithm" type="xs:string" 
       use="required" />
                  </xs:complexType>
                </xs:element>
                <xs:element name="DigestValue" type="xs:string" />
              </xs:sequence>
              <xs:attribute name="Id" type="xs:string" use="optional" />
              <xs:attribute name="URI" type="xs:string" use="required" />
              <xs:attribute name="Type" type="xs:string" use="optional" />
            </xs:complexType>
          </xs:element>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
    <xs:element name="SignatureValue" type="xs:string" />
    <xs:element name="KeyInfo">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="X509Data">
            <xs:complexType>
              <xs:sequence>
                <xs:element maxOccurs="unbounded" name="X509Certificate" 
     type="xs:string" />
              </xs:sequence>
            </xs:complexType>
            </xs:element>
           </xs:sequence>
          </xs:complexType>
          </xs:element>
         </xs:sequence>
        <xs:attribute name="Id" type="xs:string" use="required" />
      </xs:complexType>
     </xs:element>
  </xs:schema>
2
  • Es modificar su método FirmaXadesEPES y que considere el prefijo.
    – Davlio
    Commented el 31 ene. 2018 a las 14:56
  • Si construyo un archivo de esquema debo serializar ese archivo en una clase y la verdad no es lo que nesecito, pero creo que puedo agregar NameSpace para que esos nodos obtengan el prefijo implicitamente ...@Davilio sabes como hacerlo ?? Commented el 31 ene. 2018 a las 19:58
0

No se si es a esto que te refieres pero yo agrego esto en mis etiquetas xml por Ej.

XmlElement oSignature;
string pNamespacePrefix = "ds";

// Registrar el Namespace
oNamespaces.AddNamespace(pNamespacePrefix, SignedXml.XmlDsigNamespaceUrl);
var oNamespaces = new XmlNamespaceManager(xmlDocument.NameTable);

oSignature = xmlDocument.CreateElement(pNamespacePrefix, "Signature", SignedXml.XmlDsigNamespaceUrl);
2
  • Ok...Pero no se como agregar el prefijo... por que si te fijas todos los nodos son agregados por esta linea SignedXml signedXml = new SignedXml(xmlDoc); no se donde agregar tu codigo.. Commented el 4 feb. 2018 a las 19:03
  • //Continuando... // Registrar el Namespace oNamespaces.AddNamespace(pNamespacePrefix,SignedXml.XmlDsigNamespaceUrl);
    – JulioC
    Commented el 6 feb. 2018 a las 13:39

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.