Good afternoon.
I'm trying to sign the XML, however I'm having the error below:
Error generating System.Security.Cryptography.CryptographicException: Malformed Reference Element.
Searching, I saw that the problem is in the referring line.uri="#" + id;
The id variable is set to the value "ID1122632750001052017122616320300001"
Has anyone experienced anything like this?
Follow the code:
public static void GeraXMLAssinado(String caminho){
XmlDocument doc = new XmlDocument();
doc.Load(caminho);
XmlNodeList ListInfNFe = doc.GetElementsByTagName("evento");
foreach (XmlElement infNFe in ListInfNFe)
{
string id = infNFe.Attributes.GetNamedItem("Id").Value;
SignedXml xml = new SignedXml(infNFe);
xml.SigningKey = AssinaXMl().PrivateKey;
// Transformações p/ DigestValue da Nota
Reference reference = new Reference();
reference.Uri = "#" + id;
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigC14NTransform());
xml.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(AssinaXMl()));
xml.KeyInfo = keyInfo;
xml.ComputeSignature();
XmlElement xmlSignature = doc.CreateElement("Signature", "http://www.w3.org/2000/09/xmldsig#");
XmlElement xmlSignedInfo = xml.SignedInfo.GetXml();
XmlElement xmlKeyInfo = xml.KeyInfo.GetXml();
XmlElement xmlSignatureValue = doc.CreateElement("SignatureValue", xmlSignature.NamespaceURI);
string signBase64 = Convert.ToBase64String(xml.Signature.SignatureValue);
XmlText text = doc.CreateTextNode(signBase64);
xmlSignatureValue.AppendChild(text);
xmlSignature.AppendChild(xmlSignatureValue);
xmlSignature.AppendChild(doc.ImportNode(xmlSignedInfo, true));
xmlSignature.AppendChild(doc.ImportNode(xmlKeyInfo, true));
doc.AppendChild(xmlSignature);
doc.Save(caminho);
}
}