I have a c # code that generates an xml with the digital signature, but when calling the function signedXml.ComputeSignature()
it shows the following error:
Malformed Reference Element.
However, I searched for this error and most sites or forums mention removal of the KB3136000 update, except that windows 10 I'm using does not have this update installed .
What can it be?
Follow the code below highlighting the error line:
public static void AssinaDocumento(X509Certificate2 certificadoDigital, string Uri, string xmlOrigem)
{
int countTagsUri;
XmlDocument xmlDocument = new XmlDocument();
XmlDocument xmlDocument2 = new XmlDocument();
xmlDocument.PreserveWhitespace = false;
XmlNodeList xmlNodeList;
Reference reference = new Reference();
xmlDocument.Load(xmlOrigem);
xmlDocument2 = xmlDocument;
XmlDocument xmlAssinado = xmlDocument;
SignedXml signedXml = new SignedXml(xmlDocument);
signedXml.SigningKey = certificadoDigital.PrivateKey;
countTagsUri = xmlDocument.GetElementsByTagName(Uri).Count;
if (countTagsUri == 0)
{
throw new Exception("Uri " + Uri + " não encontrada no XML");
}
xmlNodeList = xmlDocument.GetElementsByTagName(Uri);
foreach (XmlNode xmlnl in xmlNodeList)
{
XmlAttributeCollection attributeCollection = xmlnl.FirstChild.Attributes;
reference.Uri = "#" + attributeCollection["id"].InnerText;
string res = xmlnl.OuterXml;
XmlDsigEnvelopedSignatureTransform envelope = new XmlDsigEnvelopedSignatureTransform();
XmlDsigC14NTransform c14NTransform = new XmlDsigC14NTransform();
KeyInfo keyInfo = new KeyInfo();
reference.AddTransform(envelope);
reference.AddTransform(c14NTransform);
signedXml.AddReference(reference);
keyInfo.AddClause(new KeyInfoX509Data(certificadoDigital));
signedXml.KeyInfo = keyInfo;
signedXml.ComputeSignature(); // O erro Ocorre aqui
XmlElement xmlDigitalSignature = signedXml.GetXml();
XmlNode xmlNode = xmlDocument.ImportNode(xmlDigitalSignature, true);
xmlDocument.FirstChild.NextSibling.LastChild.InsertAfter(xmlNode, xmlnl.LastChild);
xmlDocument.PreserveWhitespace = true;
xmlDocument.Save(@"C:\Users\ter0038\Desktop\assinado.xml");
}
}