Hi @Alexi Tomala , Welcome to Microsoft Q&A,
The current way of decoding certificates is incorrect. Base64 encoded certificates should be decoded into byte arrays instead of using UTF-8 encoding.
When loading and verifying signatures, make sure you verify the entire document, not just the signature node.
using System;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;
public class Program
{
public static void Main(string[] args)
{
string xmlFilePath = @"d:\Sob_219999830019_Ej_Mod_19072016.xml"; //args[0];
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load(xmlFilePath);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("DGICFE", "http://cfe.dgi.gub.uy");
XmlNode certificateNode = xmlDoc.SelectSingleNode("//DGICFE:Caratula/DGICFE:X509Certificate", nsmgr);
if (certificateNode != null)
{
string certificateBase64 = certificateNode.InnerText;
byte[] certificateData = Convert.FromBase64String(certificateBase64);
X509Certificate2 dcert2 = new X509Certificate2(certificateData);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");
foreach (XmlElement element in nodeList)
{
SignedXml signedXml = new SignedXml(xmlDoc);
signedXml.LoadXml(element);
bool passes = signedXml.CheckSignature(dcert2, true);
if (passes)
{
Console.WriteLine("Signature verified successfully.");
}
else
{
Console.WriteLine("Failed to verify signature.");
}
}
}
else
{
Console.WriteLine("Certificate node not found.");
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.