2
I am developing a C# application for the EFD-Reinf and at the time of sending my R-1000 event I am receiving the following message:
"A Xmldocument Context is Needed for Enveloped Transformations."
Follow my code below:
public XmlDocument Assinar(string XMLString, X509Certificate2 X509Cert)
{
//XmlDocument XMLDoc = null;
string x = X509Cert.GetKeyAlgorithm().ToString();
// Create a new XML document.
XmlDocument doc = new XmlDocument();
// Format the document to ignore white spaces.
doc.PreserveWhitespace = false;
// Load the passed XML file using it's name.
doc.PreserveWhitespace = false;
byte[] encodedString = Encoding.UTF8.GetBytes(XMLString.Trim());
MemoryStream ms = new MemoryStream(encodedString);
ms.Flush();
ms.Position = 0;
doc.Load(ms);
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(doc);
// Add the key to the SignedXml document.
signedXml.SigningKey = X509Cert.PrivateKey;
// Create a reference to be signed.
Reference reference = new Reference();
// pega o uri que deve ser assinada
XmlAttributeCollection _Uri = doc.GetElementsByTagName("ReinfEvtInfoContriInfoContri").Item(0).Attributes;
foreach (XmlAttribute _atributo in _Uri)
{
if (_atributo.Name == "id")
{
reference.Uri = "#" + _atributo.InnerText;
}
}
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(X509Cert));
signedXml.KeyInfo = keyInfo;
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
if (doc.FirstChild is XmlDeclaration)
{
doc.RemoveChild(doc.FirstChild);
}
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.PreserveWhitespace = false;
XMLDoc = doc;
return XMLDoc;
}
Does anyone know why I’m getting this mistake?
Peter, thank you for the collaboration. After using as you guided, I now get an error from "Badly formed Reference Element." in the line "signedXml.Computesignature()" You know what might be causing this error?
– User1012
Are you using the signature function that I posted or made a change to? What are you saying in the parameter
refUri
? It must be exactly equal to the attributeid
of the elementevtInfoContri
from your XML of the R-1000 event.– Pedro Gaspar