Signature namespace prefix
-
Thursday, August 21, 2008 5:20 PM
Hi,
i am signing XMLs:
....code....
MySignature.ComputeSignature()
MyXmlElement=MySignature.GetXml()
and i obtain the famous "<Signature xmlns=http://www.w3.org/2000/09/xmldsig#>" etc...
How can i obtain "<ds
ignature xmlns
s=http://www.w3.org/2000/09/xmldsig#>" ?(Note: before ComputeSignature() it is not possible making changes, you know)
I'm very tired surfing for all over the web.
I will pray for a solution (i'm been reading in a lot of forums, etc) haha.
All Replies
-
Thursday, August 21, 2008 5:25 PM
SORRY:
Hi,
i am signing XMLs:
....code....
MySignature.ComputeSignature()
MyXmlElement=MySignature.GetXml()
and i obtain the famous "<Signature xmlns=http://www.w3.org/2000/09/xmldsig#>" etc...
How can i obtain "<ds
ignature xmlns
s=http://www.w3.org/2000/09/xmldsig#>" ?(Note: AFTER ComputeSignature() it is not possible making changes, you know)
I'm very tired surfing for all over the web.
I will pray for a solution (i'm been reading in a lot of forums, etc) haha.
-
Friday, August 22, 2008 4:20 AMModerator
From Xml point of view
<a xmlns="ns1" />
and
<xx:a xmlns:xx="ns1" />
are equivalent. This seems to be the case in your situation. Why does it make a difference?
Pawel
-
Friday, August 22, 2008 3:06 PM
Thanks for reply.
I explain:
I am signing XMLs for a very important spanish government agency.
They have a XML for testing. I you don´t give it like that, errors occurs.
I have been testing with namespaces, tranforms, etc. (See at the end the las test)
Code Snippet<?
xml version="1.0" encoding="UTF-8"?><
namespace:Facturae xmlns:namespace="http://www.facturae.es/Facturae/2007/v3.0/Facturae" xmlns:namespace2="http://uri.etsi.org/01903/v1.2.2#" xmlns:namespace3="http://www.w3.org/2000/09/xmldsig#"><FileHeader><SchemaVersion>3.0</SchemaVersion><Modality>I</Modality><InvoiceIssuerType>EM</InvoiceIssuerType><Batch><BatchIdentifier>A0952171710</BatchIdentifier><InvoicesCount>1</InvoicesCount><TotalInvoicesAmount><TotalAmount>266.80</TotalAmount>
<more tags...>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:etsi="http://uri.etsi.org/01903/v1.2.2#" Id="Signature">
<
ds:SignedInfo Id="Signature-SignedInfo"><
ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></ds:CanonicalizationMethod><
ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod><
ds:Reference Id="SignedPropertiesID" Type="http://uri.etsi.org/01903/v1.2.2#SignedProperties" URI="#Signature-SignedProperties"><
ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><
ds:DigestValue>E70IIZJgM5B3rTwGJ5b4hEeJ8N0=</ds:DigestValue></
ds:Reference><
ds:Reference URI=""><
ds:Transforms><
ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform></
ds:Transforms><
ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><
ds:DigestValue>q54/ZNHSjMWKMD4A5xI9qL2tBOA=</ds:DigestValue></
ds:Reference><
ds:Reference URI="#Certificate1"><
ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><
ds:DigestValue>njihA04aMjUOyc0gnw6mfxjsfv8=</ds:DigestValue></
ds:Reference></
ds:SignedInfo><
ds:SignatureValue Id="SignatureValue">nfmak7CHtweDx/WkwizYHuNgL37d6QEyNkLIC99zK0Yar0fGtXzrKgKMSRQXdXX52ZtzdKKIB7+Q
dUA9zCWUQlwAofPtbFCNYr8Ju3KDekmqEE3oTN9T689jTzW9Mn9fsazBIaCVI/wgfv4PvS0Z+lNH
ZIjb2UlCaZeVfdeInNo=
</
ds:SignatureValue><
ds:KeyInfo Id="Certificate1"><
ds:X509Data><
ds:X509Certificate>MIID4DCCA0mg ...etc...
</ds:X509Certificate></
ds:X509Data><
ds:KeyValue><
ds:RSAKeyValue><
ds:Modulus>uJRxVtM3TvuepDYf41qgagTbuf3HYsCsB+JD7Yn47nGlfWPRLKp1Spxc0vgsrr/oYlaqP3eaQcR/
tzdIFe+rrxu99pRQFBI4hs+pQaMDiSQr2Bz9vHk12SB+plKE2zsStkVAM2GjdDa7ZcEZYF6ui/qk
5OavOMT7za9Ri8i75H0=
</
ds:Modulus><
ds:Exponent>AQAB</ds:Exponent></
ds:RSAKeyValue></
ds:KeyValue></
ds:KeyInfo><
ds:Object Id="Signature-Object"><etsi:QualifyingProperties Target="#Signature"><etsi:SignedProperties Id="Signature-SignedProperties"><etsi:SignedSignatureProperties><etsi:SigningTime>2007-12-11T19:21:28.229+01:00</etsi:SigningTime><etsi:SigningCertificate><etsi:Cert><etsi:CertDigest><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><ds:DigestValue>dDucu0BjFAIFCeiJpfVJOqAnsNk=</ds:DigestValue></etsi:CertDigest><etsi:IssuerSerial><ds:X509IssuerName>CN=CA usuarios,OU=MITyC DNIe Pruebas,O=MITyC,L=Madrid,ST=Madrid,C=ES</ds:X509IssuerName><ds:X509SerialNumber>58</ds:X509SerialNumber></etsi:IssuerSerial></etsi:Cert></etsi:SigningCertificate><etsi:SignaturePolicyIdentifier><etsi:SignaturePolicyId><etsi:SigPolicyId><etsi:Identifier>http://www.facturae.es/politica de firma formato facturae/politica de firma formato facturae v3_0.pdf</etsi:Identifier><etsi:Description>Pol¡tica de firma electr¢nica para facturaci¢n electr¢nica con formato Facturae</etsi:Description></etsi:SigPolicyId><etsi:SigPolicyHash><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><ds:DigestValue>HQvPemjDslVpcNmaJPpbHzhdZ50=</ds:DigestValue></etsi:SigPolicyHash></etsi:SignaturePolicyId></etsi:SignaturePolicyIdentifier><etsi:SignerRole><etsi:ClaimedRoles><etsi:ClaimedRole>emisor</etsi:ClaimedRole></etsi:ClaimedRoles></etsi:SignerRole></etsi:SignedSignatureProperties></etsi:SignedProperties></etsi:QualifyingProperties></ds:Object></ds:Signature>
</namespace:Facturae>
Ultimate test:
Dim t = New XmlDsigXsltTransform() Dim xel As New XmlDocumentxel.Load(
"Signature.xsd")' <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
' xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
' <xsl:output method="xml" indent="yes"/>
' <xsl:template match="/">
' <xsl:apply-templates select="node()"/>
' </xsl:template>
' <xsl:template match="*">
' <xsl:element name="ds:{local-name()}">
' <xsl:apply-templates select="@*"/>
' <xsl:apply-templates select="node()"/>
' </xsl:element>
' </xsl:template>
' <xsl:template match="*[namespace-uri() != 'http://www.w3.org/2000/09/xmldsig#']">
' <xsl:copy>
' <xsl:apply-templates select="@*"/>
' <xsl:apply-templates select="node()"/>
' </xsl:copy>
' </xsl:template>
' <xsl:template match="@*">
' <xsl:copy >
' <xsl:apply-templates select="node()"/>
' </xsl:copy>
' </xsl:template>
' </xsl:stylesheet>t.LoadInnerXml(xel.ChildNodes)
StrRef =
"http://www.w3.org/2000/09/xmldsig#Signature"docRef =
New Reference(StrRef)docRef.AddTransform(t)
sig.AddReference(docRef)
...etc...
sig.ComputeSignature()
[error]
At this moment I thing that Microsoft Framework can not do it.
Thank you, Pawel.
-
Monday, August 25, 2008 5:59 AMModerator
Will it work if you use the following Xslt stylesheet ?
Code Snippet<
xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
xsl:output method="xml" indent="yes"/><
xsl:template match="* | text()"><
xsl:copy><
xsl:copy-of select="@*"/><
<
xsl:apply-templates select="node()" /></
xsl:copy></
xsl:template><xsl:template match="*[namespace-uri() = 'http://www.w3.org/2000/09/xmldsig#']">
<xsl:element name="{local-name()}" namespace="{namespace-uri()}">
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Pawel
-
Monday, August 25, 2008 8:21 AMGood morning Pawel,
It don´t works.
I got the same errors.
"For security reasons DTD is banned in this XML document. To enable the prosecution to establish ownership DTD ProhibitDtd in XmlReaderSettings as false and wipe the method XmlReader.Create."
Trace:
en System.Xml.XmlTextReaderImpl.Throw(Exception e)
en System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res, String arg)
en System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
en System.Xml.XmlTextReaderImpl.ParseDocumentContent()
en System.Xml.XmlTextReaderImpl.Read()
en System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
en System.Xml.XPath.XPathDocument..ctor(XmlReader reader, XmlSpace space)
en System.Security.Cryptography.Xml.XmlDsigXsltTransform.GetOutput()
en System.Security.Cryptography.Xml.TransformChain.TransformToOctetStream(Object inputObject, Type inputType, XmlResolver resolver, String baseUri)
en System.Security.Cryptography.Xml.TransformChain.TransformToOctetStream(Stream input, XmlResolver resolver, String baseUri)
en System.Security.Cryptography.Xml.Reference.CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList)
en System.Security.Cryptography.Xml.SignedXml.BuildDigestedReferences()
en System.Security.Cryptography.Xml.SignedXml.ComputeSignature()I'm depressed.Thank you. -
Monday, August 25, 2008 2:03 PMModerator
I don't think the error you receive is related to stylesheet. I believe the following code is causing you the problem:
StrRef = "http://www.w3.org/2000/09/xmldsig#Signature"
docRef =
New Reference(StrRef)docRef.AddTransform(t)
sig.AddReference(docRef)
I am not sure why you add a reference to http://www.w3.org/2000/09/xmldsig#Signature (is this the document you are trying to sign?) but this document contains a DTD. By default DTD is prohibited. Let me know if you really need to add this reference (if so I think you could pre-load the document and then use Reference.LoadXml method to add it to reference).
I also looked at the code you posted and it is not complete. As a result I have a problem to fully reproduce the issue. If you send a minimal but complete repro it would be much easier to help.
Thanks
Pawel
-
Tuesday, August 26, 2008 8:50 AM
Good morning, Pawel.
Here you are the complete code:
Code SnippetDim docToSign As XmlDocument = New XmlDocument()
docToSign.PreserveWhitespace =
TruedocToSign.LoadXml(
"<invoice><data>my invoice data</data></invoice>")Dim x509 As X509Certificate2
x509 = GetMyCertificate()
Dim sig As SignedXml = New SignedXml(docToSign)
sig.SigningKey = x509.PrivateKey
Dim docRef As Reference = New Reference("") Dim trns = New XmlDsigC14NWithCommentsTransform()docRef.AddTransform(trns)
trns =
New XmlDsigEnvelopedSignatureTransform(True)docRef.AddTransform(trns)
sig.AddReference(docRef)
Dim t = New XmlDsigXsltTransform() Dim xel As New XmlDocumentxel.Load(
"Signature.xsd")t.LoadInnerXml(xel.ChildNodes)
StrRef = "
http://www.w3.org/2000/09/xmldsig#Signature" 'I want to apply the trans to the signature nodedocRef =
New Reference(StrRef)docRef.AddTransform(t)
sig.AddReference(docRef)
sig.ComputeSignature() [ERROR]
Dim xmlDigitalSignature As XmlElementxmlDigitalSignature = sig.GetXml()
Console.Write(xmlDigitalSignature.OuterXML)
Any idea?
Thank you.
-
Wednesday, August 27, 2008 6:26 AMModerator
I looked into this a bit and my understanding is (note that I am learning this security stuff) that subsequent references are transforms applied to the source document. GetXml() seems to return signature of the document after applying all the transform. In the code above the chain of transforms looks as follows:
- XmlDsigC14WithCommentsTransform
- XlmDsigEnvelopedSignatureTransform
- XmlDsigXsltTransform
GetXml() would return a signature of the SignedXml after applying these transform in this particular order.
I believe that adding Reference("http://www.w3.org/2000/09/xmldsig#Signature") as a transform means: "Transform signedXml document with the referenced file". Since the referenced file is not a valid transform (moreover it contains DTD) ComputeSignature fails. (Again, this is how I understand it works and I am still learning). I don think you can apply transformation to signature node in this scenario since the signature is being created after the actual transformation takes place... I wonder what result you expected after running your program? This is what I received:
My app built based on your app:
Code SnippetPublic
Module Module1Sub Main()
Dim docToSign As XmlDocument = New XmlDocument()
docToSign.PreserveWhitespace = True
docToSign.LoadXml(
"my invoice data") Dim x509 As X509Certificate2x509 = GetMyCertificate()
End If Next cDim sig As SignedXml = New SignedXml(docToSign)
sig.SigningKey = x509.PrivateKey
Dim docRef As Reference = New Reference("")
Dim trns = New XmlDsigEnvelopedSignatureTransform()
docRef.AddTransform(trns)
Dim t As XmlDsigXsltTransform = GetXmlDsigXsltTransform()
docRef.AddTransform(t)
sig.AddReference(docRef)
sig.ComputeSignature()
Console.Write(sig.GetXml().OuterXml)
End Sub
Function GetMyCertificate() As X509Certificate2
Dim store As New X509Store(StoreLocation.CurrentUser)store.Open(OpenFlags.ReadOnly)
Dim certCollection As X509Certificate2Collection = store.Certificates Dim cert As X509Certificate2 = Nothing Dim c As X509Certificate2 For Each c In certCollection
If c.Subject = "CN=XML_ENC_TEST_CERT" Then
Exit Forcert = c
store.Close()
GetMyCertificate = cert
End Function
Function GetXmlDsigXsltTransform() As XmlDsigXsltTransform
Dim xmlDoc As New XmlDocumentxmlDoc.LoadXml( _
""
& _""
& _""
& _""
& _""
& _""
& _""
& _""
& _""
& _""
& _""
& _""
& _""
& _""
& _""
)
Dim transform As New XmlDsigXsltTransform()transform.LoadInnerXml(xmlDoc.ChildNodes)
GetXmlDsigXsltTransform = transform
End FunctionEnd
Moduleand the result (I formatted this to be easier to read):
Code Snippet<
Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
SignedInfo><
CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><
<
SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><
Reference URI="">
Transforms><
Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /><
<
Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"><
xsl:output method="xml" indent="yes" /><
<xsl:template match="* | text()">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:apply-templates select="node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="*[namespace-uri() = 'http://www.w3.org/2000/09/xmldsig#']">
<xsl:element name="{local-name()}" namespace="{namespace-uri()}">
<xsl:copy-of select="@*" />
<xsl:apply-templates select="node()" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
</Transform>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>1H1bLJHnEnISUZ/d3pZKgExQ5aE=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>j2HVkIbJ0S9l45nKaJBnPZmrxKjZGyGsIYo6LlOB7WQZo22PayBy4O87S7Zq78y6r6v34zmAc4MuZuvW7GKb1kYJ+yFFee4Qd1gXzO8mbK+dDRyp+mZdZYaeMD/HHcp0AyNyTh3FNzW/lxfiYoKI7NI7sh2oBxvhNYhhuHUJ9OU=</SignatureValue>
</Signature>
If you really need to have the source xml transformed you may take a look here http://msdn.microsoft.com/en-us/library/system.security.cryptography.xml.xmldsigxslttransform.aspx - there are two scenarios described in the doc one of whichis actual transformation.
Also here you can find a blog posts on this. May be this will clarify how it works.
Hope this helps
Pawel
Pawel
-
Wednesday, August 27, 2008 9:37 AM
Thank you, Pawel.
Don´t forget the main question: the 'ds' prefix.
Calling to somebody in all over the the Word:
How can i obtain (with .NET Framework)
I THINK MICROSOFT FRAMEWORK CAN NOT DO IT.
I HAVE NO EXIT!
I will have to exit somehow (i am working for a very important state agency)..

-
Wednesday, August 27, 2008 2:59 PMModerator
I think I am a bit lost - I need some clarification about what you are trying to accomplish. I am starting to have the impression that the scenario is different from what I think it was. Now, I think you want to do the following:
1) Sign an Xml file
2) Transform the signature of the file (i.e. after the file is signed) so that it uses prefixed element names for elements from
http://www.w3.org/2000/09/xmldsig# namespace.
If this is the case you should just sign the file without XmlDsigXsltTransform (this transform applies stylesheet to the SignedXml document not the signature itself). As soon as you have your signature (step 1 from above is completed) (you get it using GetXml() method on SignedXml object) you can transform it using regular XslCompiledTransform object - this is step 2. This is the stylesheed that transform the signature from non-prefixed to prefixed form:
Code Snippet<
xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><
xsl:output method="xml" indent="yes" />
xsl:template match="* | text()"><
xsl:copy><
xsl:copy-of select="@*" /><
<
xsl:apply-templates select="node()" /></< FONT>xsl:copy>
</< FONT>xsl:template>
<
xsl:template match="*[namespace-uri() = 'http://www.w3.org/2000/09/xmldsig#']">
xsl:element name="ds:{local-name()}" namespace="{namespace-uri()}"><
xsl:copy-of select="@*" /><
<
xsl:apply-templates select="node()" /></< FONT>xsl:element>
</< FONT>xsl:template>
</< FONT>xsl:stylesheet>
The code would look like as follows (stylesheet.xslt is the stylesheet from above. signedXml is the xml document that was signed (SignedXml object):
XslCompiledTransform xslt = new XslCompiledTransform();
XslCompiledTransform.Load("stylesheet.xslt");
xslt.Transform(new XmlTextReader(new StringReader(signedXml.GetXml().OuterXml)), null, Console.Out);
My original signature was this:
Code Snippet<
Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><
SignedInfo><
CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><
SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><
Reference URI=""><
Transforms><
Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></< FONT>Transforms>
<
DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><
DigestValue>1H1bLJHnEnISUZ/d3pZKgExQ5aE=</< FONT>DigestValue></< FONT>Reference>
</< FONT>SignedInfo>
<
SignatureValue>j2HVkIbJ0S9l45nKaJBnPZmrxKjZGyGsIYo6LlOB7WQZo22PayBy4O87S7Zq78y6r6v34zmAc4MuZuvW7GKb1kYJ+yFFee4Qd1gXzO8mbK+dDRyp+mZdZYaeMD/HHcp0AyNyTh3FNzW/lxfiYoKI7NI7sh2oBxvhNYhhuHUJ9OU=</< FONT>SignatureValue></< FONT>Signature>
and the transformed one is this:
Code Snippet<?
xml version="1.0" encoding="utf-8"?><
ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><
ds:SignedInfo><
ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><
ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><
ds:Reference URI=""><
ds:Transforms><
ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></< FONT>ds:Transforms>
<
ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><
ds:DigestValue>1H1bLJHnEnISUZ/d3pZKgExQ5aE=</< FONT>ds:DigestValue></< FONT>ds:Reference>
</< FONT>ds:SignedInfo>
<
ds:SignatureValue>j2HVkIbJ0S9l45nKaJBnPZmrxKjZGyGsIYo6LlOB7WQZo22PayBy4O87S7Zq78y6r6v34zmAc4MuZuvW7GKb1kYJ+yFFee4Qd1gXzO8mbK+dDRyp+mZdZYaeMD/HHcp0AyNyTh3FNzW/lxfiYoKI7NI7sh2oBxvhNYhhuHUJ9OU=</< FONT>ds:SignatureValue></< FONT>ds:Signature>
Hopefully this is what you are looking for.
Pawel
-
Wednesday, August 27, 2008 3:01 PMModerator
The forum software corrupted the files. I am posting the xslt stylesheet once again - hopefully it won't get corrupted this time:
Code Snippet<
xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><xsl:output method="xml" indent="yes" />
<xsl:template match="* | text()">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:apply-templates select="node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="*[namespace-uri() = 'http://www.w3.org/2000/09/xmldsig#']">
<xsl:element name="ds:{local-name()}" namespace="{namespace-uri()}">
<xsl:copy-of select="@*" />
<xsl:apply-templates select="node()" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Pawel -
Thursday, August 28, 2008 8:37 AM
Good morning, Pawel.
Are you sure that we can modify the signature AFTER signing ?
-
Friday, August 29, 2008 7:07 AM
Buenos días Almeria, veo que estas liado con el tenma de la firma con Xades. Estoy empezando con este tema y lo estoy tomando como una estensión de XMLDSig. Lo estoy intentando desarrollar en VB.NET pero tengo dos problemas:
Al añadir una referencia a la etiqueta KeyInfo y realizar el "ComputeSignature" me dice que el XML esta mal formado
Por otro lado las propiedades de la firma para Xades tienen que ir en dentro de un Object, como compones la estructura de las propiedades de la firma
Dim referenceKey As New System.Security.Cryptography.Xml.Reference()referenceKey.Uri =
"#KeyInfo-2008"referenceKey.AddTransform(
New XmlDsigEnvelopedSignatureTransform())referenceKey.AddTransform(
New XmlDsigC14NTransform())signedXml.AddReference(referenceKey)
'Añadimos KeyInfo. Dim keyInfo As New KeyInfokeyInfo.Id =
"KeyInfo-2008"Un saludo y gracias....
-
Friday, August 29, 2008 7:33 AM
Hola,
¿Te has mirado la política de firma Facturae 3.1?
Esas transformaciones se hacen al documento en sí (URI="")
Intenta firmar antes sin Xades y prueba a ver si conseguimos el dichoso prefijo.
A ver que te parece esto:
Code SnippetDim StrRef As String = ""
Dim docRef As Reference = New Reference(StrRef) 'EL MISMO
'TRANSFORMACIONES
Dim trns = New XmlDsigC14NWithCommentsTransform()
docRef.AddTransform(trns)
trns = New XmlDsigEnvelopedSignatureTransform(True)
docRef.AddTransform(trns)
sig.AddReference(docRef)
'PROPIEDADES DE LA FIRMA
StrRef = "http://uri.etsi.org/01903/v1.2.2#SignedProperties"
docRef = New Reference(StrRef)
sig.AddReference(docRef)'PROPIEDADES DE LA CODIFICACION
StrRef = "http://www.w3.org/2000/09/xmldsig#KeyInfo"
docRef = New Reference(StrRef)
sig.AddReference(docRef)'CONSTRUIR KEYINFO
sig.KeyInfo = New KeyInfo()
sig.KeyInfo.AddClause(New KeyInfoX509Data(MiCert_x509, X509IncludeOption.ExcludeRoot))
sig.KeyInfo.AddClause(New RSAKeyValue(MiCert_x509.PrivateKey))'AHORA METEMOS XADES BASICO Y MAS TARDE AVANZADO
'Esto no funcionará sin un nodo con "http://uri.etsi.org/01903/v1.2.2#SignedProperties"
'*************************************************************************
'FORMATO FIRMA ELECTRONICA AVANZADA BASICO
'*************************************************************************
'CONSTRUIMOS FRAGMENTO XADES-EPES Y LO ADAPTAMOS A FACTURAE
'<ds:Object> | | |
' <QualifyingProperties> | | |
' <SignedProperties> | | |
' <SignedSignatureProperties> | | |
' (SigningTime)? | | |
' (SigningCertificate)? | | |
' (SignaturePolicyIdentifier)? | | |
' (SignatureProductionPlace)? | | | ESTE NO
' (SignerRole)? | | |
' </SignedSignatureProperties> | | |
' <SignedDataObjectProperties> | | | ESTE NO
' (DataObjectFormat)* | | |
' (CommitmentTypeIndication)* | | |
' (AllDataObjectsTimeStamp)* | | |
' (IndividualDataObjectsTimeStamp)* | | |
' </SignedDataObjectProperties> | | |
' </SignedProperties> | | |
' </QualifyingProperties> | | |
'</ds:Object> | | |
'</ds:Signature>- - - - - - - - - - - - - - --+-+-+
' | | |
' XAdES-BES(-EPES) | |
' | |
' XAdES-T |
' |
' XAdES(-C)
'NOTE 1: As a minimum, the signer will provide the XAdES-BES or when indicating that the signature conforms to
'an explicit signing policy the XAdES-EPES.
sig.ComputeSignature()Un saludo.
-
Friday, August 29, 2008 8:02 AM
Hola de nuevo,
sin Xades consigo firmar sin problema, pero en mi caso no es necesario el prefijo ds, me realiza la firma bien.
En cuanto a la referencia he dicho lo que me comentas de poner en la referencia
http://www.w3.org/2000/09/xmldsig#KeyInfo pero me aparece el siguiente error, The remote server returned an error: (407) Proxy Authentication Required.
'Asigno la clave privada del certificado que se usará para firmar
signedXml.SigningKey = oCertificado.PrivateKey
signedXml.Signature.Id =
"Signature-2008-04-11-13-57-48-692011104"
Dim reference As New System.Security.Cryptography.Xml.Reference()reference.Uri =
"" 'Se añaden las transformaciones que se aplicarán a la referencia.reference.AddTransform(
New XmlDsigEnvelopedSignatureTransform())reference.AddTransform(
New XmlDsigC14NTransform()) ''Añadimos la referencia.signedXml.AddReference(reference)
Dim referenceXades As New System.Security.Cryptography.Xml.Reference()referenceXades.Uri =
"#PropiedadesXades"referenceXades.Type =
"http://uri.etsi.org/01903/v1.3.2#SignedProperties"referenceXades.AddTransform(
New XmlDsigC14NTransform())signedXml.AddReference(referenceXades)
'Dim referenceKey As New System.Security.Cryptography.Xml.Reference() 'referenceKey.Uri = "#KeyInfo-2008-04-11-13-57-48-692011104" 'referenceKey.AddTransform(New XmlDsigC14NTransform()) 'signedXml.AddReference(referenceKey)------NUEVO----
Dim StrRef As String = "http://www.w3.org/2000/09/xmldsig#KeyInfo" Dim docRef As Reference = New Reference(StrRef)signedXml.AddReference(docRef)
'Añadimos KeyInfo. Dim keyInfo As New KeyInfo 'Añadimos el nombre del keyinfo Dim KeyName As New KeyInfoNameKeyName.Value = oCertificado.IssuerName.Name.ToString
keyInfo.AddClause(KeyName)
'Añadimos la clave pública del certificadokeyInfo.AddClause(
New RSAKeyValue(oCertificado.PublicKey.Key)) 'Añadimos el certificadokeyInfo.AddClause(
New KeyInfoX509Data(oCertificado, X509Certificates.X509IncludeOption.ExcludeRoot))signedXml.KeyInfo = keyInfo
En cuanto a los requerimientos de Xades me los mire, pero no se como añadir las las etiquetas requeridas de las propiedades de la firma a mi objeto xmldsig?
-
Friday, October 24, 2008 10:31 AM
Hola.
Igual el hilo está muerto, pero he empezado con este tema y estoy también desesperadillo. Pero sobre el último comentario puedo aportar algo:
No es que se quiera poner el prefijo ds: delante de cada nodo de la firma XMLDSIG es que es necesario para cumplir con lo que dice la normativa.
Igual pasa con los nodos de XAdES que se empleen, deben ir con el prefijo propio, en concreto recomienda xades:. No obstante en las firmas que he visto que hace el programa ¿del gobierno español? ponen etsi: (creo que el programa es el INTECOfirma, pero no me hagáis mucho caso que tengo un lío de normativas y siglas que no me aclaro).
Saludos.
-
Friday, October 24, 2008 10:46 AM
Hola de nuevo.
Se me olvidó comentarlo en el correo anterior.
CREO (y me guio por mi sentido común que es el menos común de los sentidos) que no hay problema de modificar el fichero de firma SIEMPRE QUE NO SE TOQUEN LOS NODOS/DATOS DEL FICHERO ORIGINAL. De hecho la firma se aplica al fichero XML original y luego se altera con los nodos de la firma.
De hecho para logar la firma XMLDSIG lo hice a mano de esta forma, sacando los datos de una firma "temporal" que hace .net y creando los nodos modificados. Probaré la idea que se ha comentado en este hilo, es mucho más limpia.
Saludos.
-
Saturday, October 25, 2008 6:35 AM
Hola,
el hilo esta vivo. En unos pocos dias tengo que retomar el tema y hacer pruebas. Ya tendréis noticias.
Saludos.
-
Monday, October 27, 2008 12:56 PM
Ok.
Saludos.
-
Wednesday, November 12, 2008 11:35 AM
Hola,
¿has salvado el error "Elemento de referencia malformado"?
Estoy ahí atrancado y no tengo más ideas.
Un saludo.
-
Friday, November 21, 2008 2:30 PMHola a todos,
A ver, llevo con esto un tiempo... y me esta volviendo loco el dichoso NAMESPACE de la firma...
Habéis descubierto algo al respecto?
Saludos,
Eliseo. -
Friday, November 21, 2008 9:24 PM
Hola,
tengo que decir que estoy hasta los mismisimos del .NET
La Agencia Tributaria ha sacado unas librerias en Java para firmar XML con Xades.
Y con .Net no tengo reaños a hacer una firma con formato Facturae.
Habrá que pasarse a JAVA....
¿Has oido Microsoft?
Saludos al hilo.
-
Tuesday, March 03, 2009 4:06 PMAny solution about it ?
alguna solución sobre este tema ? alguna librería para soporte a xades,y alguna aplicación de ejemplo con código fuente para ver cómo se firma con xades un fichero xml (factura) que se valida con un XSD (el que da facturae) ?
No he encontrado nada completo en foros de la comunidad, sólo alguna aplicación comercial.
Microsoft ha ocultado una implementación tal como indica este documento: existió Microsoft.Xades.dll, pero no se sabe donde está ahora, quizá sea una conspiración judeo-masónica.
http://download.microsoft.com/download/4/f/d/4fd49a94-8772-4bd0-88ca-bf46e2d029fc/24_JUNE_2004/MSSoftwarePresentation_ORIG.ppt
Alguien de Microsoft tiene noticas al respecto ??
saludos.
Gracias
thanks in advance
http://www.alhambra-eidos.es/web2005/index.html -
Tuesday, May 19, 2009 1:46 PMYo tenía el mismo problema para enviar datos al servicio de cambio de domicilio del MAP: exigen el prefijo ds para los nodos de la firma.
Lo he resuelto sacando el código de la clase SignedXml y construyendo mi propia clase, que añade el prefijo antes de que se calcule el hash de la firma.
Se usa igual que SignedXml pero llamando a los métodos ComputeSignature(prefix) y GetXml(prefix).
Para no complicarme la vida llamo a algún método privado por reflexión, y también he comentado un par de líneas que a mí no me hacían falta. Os dejo aquí el código por si a alguien le sirve, pero revisad las líneas que os comento...
Delia
using System; using System.Reflection; using System.Security.Cryptography.Xml; using System.Security.Cryptography; using System.Collections.Generic; using System.Text; using System.Xml; namespace XXX { public class PrefixedSignedXML : SignedXml { public PrefixedSignedXML(XmlDocument document) : base(document) { } public PrefixedSignedXML(XmlElement element) : base(element) { } public PrefixedSignedXML() : base() { } public void ComputeSignature(string prefix) { this.BuildDigestedReferences(); AsymmetricAlgorithm signingKey = this.SigningKey; if (signingKey == null) { throw new CryptographicException("Cryptography_Xml_LoadKeyFailed"); } if (this.SignedInfo.SignatureMethod == null) { if (!(signingKey is DSA)) { if (!(signingKey is RSA)) { throw new CryptographicException("Cryptography_Xml_CreatedKeyFailed"); } if (this.SignedInfo.SignatureMethod == null) { this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; } } else { this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; } } SignatureDescription description = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription; if (description == null) { throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated"); } HashAlgorithm hash = description.CreateDigest(); if (hash == null) { throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed"); } this.GetC14NDigest(hash, prefix); this.m_signature.SignatureValue = description.CreateFormatter(signingKey).CreateSignature(hash); } public XmlElement GetXml(string prefix) { XmlElement e = this.GetXml(); SetPrefix(prefix, e); return e; } //Invocar por reflexión al método privado SignedXml.BuildDigestedReferences private void BuildDigestedReferences() { Type t = typeof(SignedXml); MethodInfo m = t.GetMethod("BuildDigestedReferences", BindingFlags.NonPublic | BindingFlags.Instance); m.Invoke(this, new object[] { }); } private byte[] GetC14NDigest(HashAlgorithm hash, string prefix) { //string securityUrl = (this.m_containingDocument == null) ? null : this.m_containingDocument.BaseURI; //XmlResolver xmlResolver = new XmlSecureResolver(new XmlUrlResolver(), securityUrl); XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; XmlElement e = this.SignedInfo.GetXml(); document.AppendChild(document.ImportNode(e, true)); //CanonicalXmlNodeList namespaces = (this.m_context == null) ? null : Utils.GetPropagatedAttributes(this.m_context); //Utils.AddNamespaces(document.DocumentElement, namespaces); Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject; //canonicalizationMethodObject.Resolver = xmlResolver; //canonicalizationMethodObject.BaseURI = securityUrl; SetPrefix(prefix, document.DocumentElement); //establecemos el prefijo antes de se que calcule el hash (o de lo contrario la firma no será válida) canonicalizationMethodObject.LoadInput(document); return canonicalizationMethodObject.GetDigestedOutput(hash); } private void SetPrefix(string prefix, XmlNode node) { foreach (XmlNode n in node.ChildNodes) SetPrefix(prefix, n); node.Prefix = prefix; } } } -
Tuesday, June 16, 2009 8:31 AMHola, habeis conseguido algo???
Yo tambien estoy con un proyecto de facturae, el XML lo genero perfectamente pero la firma, imposible.
Me podeis pasar algun codigo en vb.net o en c# (ya lo convertiria yo luego) para firmar un XML pasado la ruta por parametro???
O aunque sea usando la api java de la aeat, el codigo para llamarla y el .jar de la api
Saludos desde Zaragoza
mi email es: kimosave81@hotmail.com -
Thursday, September 17, 2009 2:03 PM¿Alquien lo ha conseguido? Llevo un par de semanas intentando generar la firma XAdES y ¡no hay manera!
-
Saturday, September 19, 2009 11:09 AMModeratorHello,
Please use English on the forums. The purpose of the forum is to answer your question AND for anybody else to find and use the answer again. These forums are for english speaking people, and so having a question answered in another language defeats the purpose of the forum.
Thank you,
Vitek Karas [MSFT] -
Thursday, November 05, 2009 9:58 AM
I am also struggling with the same issue.
One of my friend suggested to add empty signature to document and sign it and then add insert signature and digest values....
Can we do so.. I read about ComputeSignature not considering any existing Signatures in document that it signs.
Vinod Bapatla Hyderabad -
Monday, June 07, 2010 9:24 AM
Hola Almeria, por favor, cosiguio usted firmar un XML con xades para la factura digital española? ... seria tan amable de enviarme algun codigo de ejemplo que tubiera para visual studio? ... muchisimas gracias.
Un saludo
fmorales -
Monday, June 07, 2010 9:27 AM
Estimado Kimosave .... me llamo francisco y soy de Malaga ... estoy un poco desesperado con el asunto de firmar un cml con xades para la factura electronica ... ¿le enviaron algun ejemplo en vb.net o c#? sería tan amable de reenviarmelo? se que hace tiempo de este post suyo, pero si no fuera porque hace mas de un mes que estoy intentando averiguar como firmar el dichoso xml no se lo pediria.
Muchas gracias, un saludo
fmorales -
Monday, June 07, 2010 12:35 PMModerator
Hi,
Please use English, not all people on this forum can speak spanish and thus won't be able to answer your question.
Thanks,
Vitek Karas [MSFT] -
Tuesday, June 08, 2010 6:55 AM
try this mister,
http://sviudes.blogspot.com/2010/05/facturae-con-net-y-c.html
- Proposed As Answer by zoyab- MSFT Wednesday, June 16, 2010 3:55 AM
- Marked As Answer by Arun Chandrasekhar - MSFTMicrosoft Employee, Moderator Thursday, May 12, 2011 6:51 AM
-
Wednesday, March 14, 2012 8:05 PM
Hi Zoyab/Arun-
How do I calidate the signature computed with ds prefix?
Thanks
-
Friday, May 25, 2012 5:17 PM
Hi Almeria,
Have you solved this issue ??
Now I m in a same situation with you when you ve written this issue.
I really need to generate xmlsignature with "ds" prefix.
Actually, I need to genererate XADES-BES format ,, so I dont know hot to generated it ??
Have you got any idea about that ??
-
Tuesday, June 05, 2012 3:55 PM
Hi
how resolved DeliZgz is good, you view thread of Tuesday, May 19, 2009 1:46 PM, applied this code and the xml signed was accepted in the server but the signature is invalid in the server. All in Visual Basic 2008 with Keytool or makecert. The server is in java for to recognize the sign.
I dont know what to do!
I need your help! Have you got any idea about this problem?
Chard
-
Thursday, June 28, 2012 8:20 PMMuchas gracias DeliaZgz, solo me queda probar si me aceptan el documento.... :)

