I am trying to modify a XML file. I already delete the part of the XML that I do not need, but now I am trying to append a node from another XML file.
This is my code to delete the node 'saml:AssertionEncrypted' from the XML file:
XmlDocument Doc = new XmlDocument();
Doc.PreserveWhitespace = true;
Doc.Load("XMLAssertionEncrypted.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(Doc.NameTable);
ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
XmlNode node = Doc.SelectSingleNode("//saml:EncryptedAssertion", ns);
var list = Doc.DocumentElement.GetElementsByTagName("saml:EncryptedAssertion").OfType<XmlElement>().ToArray();
XmlNode root = Doc.DocumentElement;
foreach(var element in list) {
var parent = element.ParentNode;
if (parent != null) {
parent.RemoveChild(element);
//parent.ReplaceChild(newNodeElement, element); //This neither works
}
}
Now, I want to add the whole Mytest.xml file into XMLAssertionEncrypted.xml, in the same position where was the node deleted before.
XmlDocument newNode = new XmlDocument();
xml.PreserveWhitespace = true;
xml.Load("Mytest.xml");
XmlNode newNodeElement = newNode.DocumentElement.SelectSingleNode("/");
root.InsertAfter(newNodeElement, root.LastChild);
I am getting the error "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."
This is "xmlAssertionEncrypted.xml" once the node is removed:
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Version="2.0" ID="mReKMQjpJ81L9Yu" IssueInstant="2019-09-11T13:29:01.254Z" Destination="https://test.com/sso.aspx">
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">saml.test.com</saml:Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
<ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
<ds:Reference URI="#mFCXf3nW6C7tzReKMQjpJ81L9Yu">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> </ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<ds:DigestValue>hwFmHiMyh07qJB88=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue> 73Z/brHijqXg3sRQGsgeZlsnH5JyBj/ADJZgCablLXHBr75wQmZi1AvsLE9e/h3+U7RMalqqx0TI bo8OXA/9ZTdJnF9zWU9hYcFhHBTPF9fGDdsFIg== </ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate> MIIGojCCBYqgAwIBAgIQCEZjQ1QTXW74RfN6KsynzjANBgkqhkiG9w0BAQsFADBEMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMR4wHAYDVQQDExVEaWdpQ2VydCBHbG9iYWwgQ0Eg RzIwHhcNMTkwMjAxMDAwMDAwWhcNMjEwMjAxMTIwMDAwWjB0MQswCQYDVQQGEwJVUzERMA8GA1UE bxAyKah48l0k7uCG4u+WOsvO9edQ+3WjLl7u7oneLqB2mXSccz545tUQJyTFZUVdaTI7E7cy
vmHkx2ubL1gnvSAQ/h5huCoc4zoFHWLdkfDpJzYwjm/rXWfhanaxYlTlYb7ExD09RuUrMS0ahcLt K2nRAx7CD6oLdH6LTCuuZNaaQloK1QBRQWSr5X1Q5v56/VeMVEs8/qd/28y+a4G+Fg== </ds:X509Certificate>
</ds:X509Data>
<ds:KeyValue>
<ds:RSAKeyValue>
<ds:Modulus> QxcV+y50B1E+oV8oHD0c+ZTN1NRGWCfFLPoRhIShIG5QaPpQy1h9E74BO2VohQPhkj9hwRC7qTIb pKXztQi0T2BERs/iDxEEHa9xzY0AjBEqvUoZ8iqbd4IoqcF0+ryWwP+rCR9FPy43aW+U0mvYn2KT N+MA0JSdhLrAD9h1KKQIpXnL64W7QDexiJaXUQ== </ds:Modulus>
<ds:Exponent>AQAB</ds:Exponent>
</ds:RSAKeyValue>
</ds:KeyValue>
</ds:KeyInfo>
</ds:Signature>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" /> </samlp:Status>
</samlp:Response>
And I would like to append the new XML node from "Mytest.xml" right after '/samlp:Status' and before '/samlp:Response'.
This is "Mytest.xml" file:
<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="zrvyPwcFJXd5nKoaGoVP24Y_KYO" IssueInstant="2019-09-11T13:29:01.257Z" Version="2.0">
<saml:Issuer>saml.test.com</saml:Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></ds:SignatureMethod>
<ds:Reference URI="#zrvyPwcFJXd5nKoaGoVP24Y_KYO">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"></ds:DigestMethod>
<ds:DigestValue>R2ho2iZU=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>
051pdJAuf2oHLQQzWN1RW0KLwATj0MRfdy0TLg==
</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate>
vmHkx2ubL1gnvSAQ/h5huCoc4zoFHWLdkfDpJzYwjm/rXWfhanaxYlTlYb7ExD09RuUrMS0ahcLt K2nRAx7CD6oLdH6LTCuuZNaaQloK1QBRQWSr5X1Q5v56/VeMVEs8/qd/28y+a4G+Fg==
</ds:X509Certificate>
</ds:X509Data>
<ds:KeyValue>
<ds:RSAKeyValue>
<ds:Modulus>
N+MA0JSdhLrAD9h1KKQIpXnL64W7QDexiJaXUQ==
</ds:Modulus>
<ds:Exponent>AQAB</ds:Exponent>
</ds:RSAKeyValue>
</ds:KeyValue>
</ds:KeyInfo>
</ds:Signature>
<saml:Subject>
<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">835</saml:NameID>
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData NotOnOrAfter="2019-09-11T13:30:01.257Z" Recipient="https://test.com/sso.aspx"></saml:SubjectConfirmationData>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2019-09-11T13:28:01.257Z" NotOnOrAfter="2019-09-11T13:30:01.257Z">
<saml:AudienceRestriction>
<saml:Audience>https://test.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2019-09-11T13:29:01.256Z" SessionIndex="P24Y_KYO">
<saml:AuthnContext>
<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
</saml:Assertion>
Related
I'm trying to replicate a behavior of SAMl signature verification from one of the system into C# and I'm trying locally on my system. However, I'm not able to crack it so far, I always get false when I try to verify the signed XML with X509 certificate.
What am I missing, and is there a way to get logs to explain why it is failing?
public static bool VerifyXml(XmlDocument Doc,X509Certificate2 cert1) {
if (Doc == null)
throw new ArgumentException("Doc");
SignedXml signedXml = new SignedXml(Doc);
var nsManager = new XmlNamespaceManager(Doc.NameTable);
nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
var node = Doc.SelectSingleNode("//ds:Signature", nsManager);
// find signature node
var certElement = Doc.SelectSingleNode("//ds:X509Certificate", nsManager);
// find certificate node
var cert = new X509Certificate2(Convert.FromBase64String(certElement.InnerText));
signedXml.LoadXml((XmlElement)node);
if (cert1.GetPublicKeyString() != cert.GetPublicKeyString())
{
Console.WriteLine("certificate verification failed.");
return false;
}
return signedXml.CheckSignature(cert);
}
Below is the SAML Response that I'm trying to verify, I have trimmed some data for security reasons:
<samlp:Response ID="_0d04b5df-77ff-4e90-9796-82b46105dbbf" Version="2.0" IssueInstant="2023-01-21T03:39:23Z" Destination="https://uat.xyz.com" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">https://idp-test.xyz.com</saml:Issuer>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
<Reference URI="#_0d04b5df-77ff-4e90-9796-82b46105dbbf">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<InclusiveNamespaces PrefixList="#default samlp saml ds xs xsi" xmlns="http://www.w3.org/2001/10/xml-exc-c14n#" />
</Transform>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<DigestValue>Vrn6ZWIg7Q3zKTbGnVdKlsfgjqmHHLv0+KilO2gAZ5s=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>MGjQp9uCT/pkHPuVKC8+8I3tbLHS7Y2fXFyoGfLpIwlNEWOqbTFzU1dco1Bzw9MsmAEen6Wq</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MIIDzTCCArWgAwIBAgIJAMIRqxzkLqE8MA0GCSqGSIb3DQEBCwUAMHwxCzAJBgNVBAYTAlVTMRAwDgYDVQQIDAdGbG9yaWRhMRYwFAYDVQQHDA1TdCBQZXRlcnNidXJnMRwwGgYDVQQKDBNLb2JpZSBNYXJrZXRpbmcgSU5DMSUwIwYDVQQDDBxj</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
<saml:Assertion Version="2.0" ID="_6d46cc16-cb04-4e44-88b3-e6a3a3d3357d" IssueInstant="2023-01-21T03:39:23Z" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Issuer>https://idp-test.xyz.com</saml:Issuer>
<saml:Subject>
<saml:NameID>e58c9aaa-9b68-4328-ad65-4f1b82086406</saml:NameID>
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData NotOnOrAfter="2023-01-21T03:42:23Z" Recipient="https://uat.xyz.com/" />
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2023-01-21T03:36:23Z" NotOnOrAfter="2023-01-21T03:42:23Z">
<saml:AudienceRestriction>
<saml:Audience>https://idp-test.xyz.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2023-01-21T03:39:23Z" SessionIndex="_6d46cc16-cb04-4e44-88b3-e6a3a3d3357d">
<saml:AuthnContext>
<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
</saml:Assertion>
</samlp:Response>
I am trying to send a request via web service (SoapHttpClientProtocol) method. Unfortunately for me, this request requires to have wsse:Security Token in soap header, with signature of request xml, and raw data of public key (as I understand).
Soap exammple how it should be:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
soap:mustUnderstand="1">
<wsse:BinarySecurityToken
EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"
wsu:Id="X509-D517D5F699516D846F15717371831011">
MIIE_certificate_raw_data_==
</wsse:BinarySecurityToken>
<wsu:Timestamp wsu:Id="TS-1">
<wsu:Created>2021-03-15T09:39:43.086Z</wsu:Created>
<wsu:Expires>2021-03-15T09:44:43.086Z</wsu:Expires>
</wsu:Timestamp>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SIG-3">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="soap"/>
</ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<ds:Reference URI="#TS-1">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wsse soap"/>
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>Digest_Value</ds:DigestValue>
</ds:Reference>
<ds:Reference URI="#id-2">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList=""/>
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>Digest_Value</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>Signature_Value</ds:SignatureValue>
<ds:KeyInfo Id="KI-D517D5F699516">
<wsse:SecurityTokenReference wsu:Id="STR-D517D5F6">
<wsse:Reference URI="#X509-D517D5F699516D846F" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
</wsse:Security>
</soap:Header>
<soap:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-2">
<Tag1>
<T>12345678</T>
<B>2342</B>
<C>3456345435</C>
</Tag1>
</soap:Body>
</soap:Envelope>
What I have done:
Created class
public class SecurityHeader : SoapHeader, IXmlSerializable
{
public XmlElement Xml { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader) { }
public void WriteXml(XmlWriter writer)
{
writer.WriteRaw(Xml.InnerXml);
}
}
added class which adds SecurityHeader
SecurityHeaderExtension : SoapExtension
into web.config:
<system.web>
</system.web>
And finally I am getting soap:Header <wsse_x003A_Security ...> instead of soap:Header <wsse:Security ...>
Can somebody give me a hand of help? I have read a lot links already, with no result at the moment...
UPD:
Partialy solved this issue by:
var requestContext = myWebService.RequestSoapContext;
var token = new Microsoft.Web.Services2.Security.Tokens.X509SecurityToken(certX);
requestContext.Security.Tokens.Add(token);
requestContext.Security.Timestamp.TtlInSeconds = 5;
// Sign the message using the X509 certificate.
var messageSign = new Microsoft.Web.Services2.Security.MessageSignature(token);
messageSign.SignatureOptions = Microsoft.Web.Services2.Security.SignatureOptions.IncludeSoapBody | Microsoft.Web.Services2.Security.SignatureOptions.IncludeTimestamp;
requestContext.Security.Elements.Add(messageSign);
var resp = myWebService.ExecuteCall(req);
Now I have problem with reading response, I am getting error: 'The signature or decryption was invalid'.
As I understand the problem is on my side, but not sure...
I want to create something like below:
<SOAP-ENV:Header>
<wsse:Security SOAP-ENV:mustUnderstand="1">
<wsse:BinarySecurityToken EncodingType="…#Base64Binary" ValueType="…#X509v3" wsu:Id="CertId-1776694">
MIIDDDCCAfSgAwIBAgIQM6YEf7FVYx/tZyEXgVComTANBgkqhkiG9w0SDGBSDJHBK34...
</wsse:BinarySecurityToken>
<ds:Signature>
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<ds:Reference URI="#id-1464350">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<ds:DigestValue">1JmC1C0FrlPB42xfFKolgaCew5k=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue">
H1b7jH2bHpbrzJXkFS0msdUYycDMH4n6m4oTRtbo4Yk35/JzGcuwUYZ3...
</ds:SignatureValue>
<ds:KeyInfo>
<wsse:SecurityTokenReference wsu:Id="STRId-13498124">
<wsse:Reference URI="#CertId-1776694" ValueType="…#X509v3" />
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
</wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body wsu:Id="id-1464350">
...
</SOAP-ENV:Body>
I have the next code:
OperationsClient client = new OperationsClient();
var response = await client.MarketInfoAsync(request);
...
internal partial class OperationsClient
{
static partial void ConfigureEndpoint(ServiceEndpoint serviceEndpoint, ClientCredentials clientCredentials)
{
serviceEndpoint.Address = new EndpointAddress("https://testmisapi.ercot.com/2007-08/Nodal/eEDS/EWS/");
(serviceEndpoint.Binding as BasicHttpBinding).Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
(serviceEndpoint.Binding as BasicHttpBinding).Security.Mode = BasicHttpSecurityMode.Transport;
clientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, 509FindType.FindBySerialNumber, "XXXXX");
}
}
I recieve the error:
SECU1075: An error was discovered processing the <wsse:Security> header
I have tried changig this:
(serviceEndpoint.Binding as BasicHttpBinding).Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
(serviceEndpoint.Binding as BasicHttpBinding).Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
But in this case I recieve following error:
Could not establish trust relationship for the SSL/TLS secure channel with authority 'testmisapi.ercot.com'.
I have read that I can use IClientMessageInspector but I don't know how can I add the complete Security header.
Thank you very much!
I'm doing the signing of a document with c #
with this code
public class program
{
static void Main(String[] arg)
{
string xmlString = File.ReadAllText(#"D:\E-Billing\Demo.xml");
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
//doc.Load(#"D:\E-Billing\Demo.xml");
string pfxStr = #"D:\E-Billing\jojolete.pfx";
X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxStr),"cabanillas");
SignedXMLWithCertificate(doc, cert);
Console.WriteLine(doc.OuterXml);
doc.Save(#"D:\E-Billing\Demo2.xml");
}
public static void SignedXMLWithCertificate(XmlDocument doc, X509Certificate2 cert)
{
SignedXml signedXML = new SignedXml(doc);
signedXML.SigningKey = cert.PrivateKey;
Reference reference = new Reference();
reference.Uri = "";
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
signedXML.AddReference(reference);
KeyInfo keyinfo = new KeyInfo();
keyinfo.AddClause(new KeyInfoX509Data(cert));
signedXML.KeyInfo = keyinfo;
signedXML.ComputeSignature();
XmlElement xmlsig = signedXML.GetXml();
//doc.DocumentElement.AppendChild(doc.ImportNode(xmlsig, true));
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ext", "");
doc.SelectSingleNode("/Invoice/ext:ExtensionContent", nsmgr).AppendChild(doc.ImportNode(xmlsig, true));
}
Xml document I want to sign has the following tags where to insert the signature
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Invoice>
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent>
<sac:AdditionalInformation>
<sac:AdditionalMonetaryTotal>
<cbc:ID>1001</cbc:ID>
<cbc:PayableAmount currencyID="PEN">348199.15</cbc:PayableAmount>
</sac:AdditionalMonetaryTotal>
<sac:AdditionalMonetaryTotal>
<cbc:ID>1003</cbc:ID>
<cbc:PayableAmount currencyID="PEN">12350.00</cbc:PayableAmount>
</sac:AdditionalMonetaryTotal>
<sac:AdditionalMonetaryTotal>
<cbc:ID>1004</cbc:ID>
<cbc:PayableAmount currencyID="PEN">30.00</cbc:PayableAmount>
</sac:AdditionalMonetaryTotal>
<sac:AdditionalMonetaryTotal>
<cbc:ID>2005</cbc:ID>
<cbc:PayableAmount currencyID="PEN">59230.51</cbc:PayableAmount>
</sac:AdditionalMonetaryTotal>
<sac:AdditionalProperty>
<cbc:ID>1000</cbc:ID>
<cbc:Value>CUATROCIENTOS VEINTITRES MIL DOSCIENTOS VEINTICINCO Y
00/100</cbc:Value>
</sac:AdditionalProperty>
</sac:AdditionalInformation>
</ext:ExtensionContent>
</ext:UBLExtension>
<ext:UBLExtension>
<ext:ExtensionContent>
<ds:Signature Id="SignatureSP">
<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#envelopedsignature"/>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>ryg5Vl+...Qjk=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>SOiGQp....ffb0=</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509SubjectName>1.2IMA,ST=LIMA,C=PE</ds:X509SubjectName>
<ds:X509Certificate>MIIESTCCAzGgAwIBAgIKWOC++GxDtaK/5EiVKSqzJ6geIfz</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</ds:Signature>
</ext:ExtensionContent>
</ext:UBLExtension>
</ext:UBLExtensions>
more tags
</Invoice>
but the tags signature appears at the end
<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" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>GF0......OR/nXwTxw=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>JQLyp...wEN6Th</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>o6pQR6K.......XJODMUu</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</Invoice>
As I can move or assign where they will sign the xml?
You can change the last line of your code
doc.DocumentElement.AppendChild(doc.ImportNode(xmlsig, true));
to
doc.SelectSingleNode("/Invoice/ext:ExtensionContent", nsmgr).AppendChild(doc.ImportNode(xmlsig, true));
The document node is the root node, so it will append there. SelectSingleNode() uses XPath to select a different node for importing. Note that you need a namespace manager for the extprefix.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ext","uri-of-ext");
I have a program that needs to validate xml signatures, I have not had any troubles until a provider sent me one xml with a strange format and my code couldn't validate it's signature.
public bool Validate(XmlDocument p_doc)
{
XmlNamespaceManager l_nsManager = new XmlNamespaceManager(new NameTable());
l_nsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
XmlElement l_signatureElement = p_doc.SelectSingleNode("//ds:Signature", l_nsManager) as XmlElement;
SignedXml l_signed = new SignedXml(p_doc);
l_signed.LoadXml(l_signatureElement);
return l_signed.CheckSignature();
}
The method CheckSignature returns false, and I know it is a valid document.
The xml I am trying to validate:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><EnvioCFE_entreEmpresas xmlns="http://cfe.dgi.gub.uy" xmlns:ns2="http://www.w3.org/2001/04/xmlenc#" xmlns:ns3="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemaLocation="http://cfe.dgi.gub.uy EnvioCFE_entreEmpresasv1.32.xsd"><Caratula version="1.0"><RutReceptor>211162510010</RutReceptor><RUCEmisor>213217030011</RUCEmisor><Idemisor>58653</Idemisor><CantCFE>1</CantCFE><Fecha>2014-10-27T09:02:01.184-03:00</Fecha><X509Certificate>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</X509Certificate></Caratula><ns2:CFE_Adenda xmlns="http://tilsor.com.uy/#StringAdenda" xmlns:ns2="http://cfe.dgi.gub.uy" xmlns:ns3="http://www.w3.org/2001/04/xmlenc#" xmlns:ns4="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://cfe.dgi.gub.uy CFEEmpresas_v1.20.xsd"><CFE xmlns="http://cfe.dgi.gub.uy" xmlns:ns2="http://www.w3.org/2001/04/xmlenc#" xmlns:ns3="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemaLocation="http://cfe.dgi.gub.uy CFEDGI_v1.19.xsd"><eFact><TmstFirma>2014-10-20T08:56:38.167-03:00</TmstFirma><Encabezado><IdDoc><TipoCFE>111</TipoCFE><Serie>A</Serie><Nro>20003</Nro><FchEmis>2014-10-16</FchEmis><PeriodoDesde>2014-06-30</PeriodoDesde><PeriodoHasta>2015-06-30</PeriodoHasta><FmaPago>1</FmaPago></IdDoc><Emisor><RUCEmisor>213217030011</RUCEmisor><RznSoc>Royal & SunAlliance (Uruguay) S.A.</RznSoc><NomComercial>Royal & SunAlliance Uruguay SA</NomComercial><GiroEmis>Seguros</GiroEmis><Telefono>29170505</Telefono><CorreoEmisor>dgi_cfe#uy.rsagroup.com</CorreoEmisor><EmiSucursal>RSA UY</EmiSucursal><CdgDGISucur>1</CdgDGISucur><DomFiscal>Sarandi 620</DomFiscal><Ciudad>Montevideo</Ciudad><Departamento>Montevideo</Departamento></Emisor><Receptor><TipoDocRecep>2</TipoDocRecep><CodPaisRecep>UY</CodPaisRecep><DocRecep>211162510010</DocRecep><RznSocRecep>PUNTO LUZ S.A.</RznSocRecep><DirRecep> SORIANO 1032</DirRecep><CiudadRecep>MONTEVIDEO</CiudadRecep><DeptoRecep>MONTEVIDEO</DeptoRecep><CP>0</CP></Receptor><Totales><TpoMoneda>UYU</TpoMoneda><TpoCambio>1.0000</TpoCambio><MntNoGrv>0.00</MntNoGrv><MntExpoyAsim>0.00</MntExpoyAsim><MntImpuestoPerc>0.00</MntImpuestoPerc><MntIVaenSusp>0.00</MntIVaenSusp><MntNetoIvaTasaMin>0.00</MntNetoIvaTasaMin><MntNetoIVATasaBasica>14754.10</MntNetoIVATasaBasica><MntNetoIVAOtra>0.00</MntNetoIVAOtra><IVATasaMin>10</IVATasaMin><IVATasaBasica>22</IVATasaBasica><MntIVATasaMin>0.00</MntIVATasaMin><MntIVATasaBasica>3245.90</MntIVATasaBasica><MntIVAOtra>0.00</MntIVAOtra><MntTotal>18000.00</MntTotal><MntTotRetenido>0.00</MntTotRetenido><CantLinDet>1</CantLinDet><MontoNF>0.00</MontoNF><MntPagar>18000.00</MntPagar></Totales></Encabezado><Detalle><Item><NroLinDet>1</NroLinDet><IndFact>3</IndFact><IndAgenteResp>R</IndAgenteResp><NomItem>DEDUCIBLE AUTOMOVILES/FLOTAS</NomItem><DscItem>POLIZA 619064</DscItem><Cantidad>1</Cantidad><UniMed>Unid</UniMed><PrecioUnitario>14754.10</PrecioUnitario><DescuentoPct>0.00</DescuentoPct><DescuentoMonto>0.00</DescuentoMonto><RecargoPct>0.00</RecargoPct><RecargoMnt>0.00</RecargoMnt><MontoItem>14754.10</MontoItem></Item></Detalle><DscRcgGlobal></DscRcgGlobal><MediosPago><MedioPago><NroLinMP>1</NroLinMP><GlosaMP>EFECTIVO</GlosaMP><ValorPago>18000.00</ValorPago></MedioPago></MediosPago><Referencia></Referencia><CAEData><CAE_ID>90140013992</CAE_ID><DNro>1</DNro><HNro>25000</HNro><FecVenc>2016-06-16</FecVenc></CAEData></eFact><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:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod>
<ds:Reference URI="">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform>
<ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
<ds:XPath>
not(ancestor-or-self::ds:Signature)
</ds:XPath>
</ds:Transform>
<ds:Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
<ds:DigestValue>Z1wbJ/j3XZ9IuC1d4SYnq2Y7pjE=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>
de1w5zlI7BdJjdBpvTR/0aaDmonR7ICEVNEjvJDGk6MsvI8vs93M+wXIDcKJvm5RuRlrlR7W0TGY
8xP1WuiChOcAl5Fje9ExrvS1HPc+5NsguDFwGCBRWxs1gZP8coTkH596/cYsscM1I7XexoRLXHWS
TdghDNUJv7vNVQFTTXU=
</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509IssuerSerial>
<ds:X509IssuerName>CN=Correo Uruguayo - CA,OU=SERVICIOS ELECTRONICOS,O=ADMINISTRACION NACIONAL DE CORREOS,C=UY</ds:X509IssuerName>
<ds:X509SerialNumber>99998921932968755343991161283803277349</ds:X509SerialNumber>
</ds:X509IssuerSerial>
</ds:X509Data>
<ds:KeyValue>
<ds:RSAKeyValue>
<ds:Modulus>qhNCuOvb7x4Yr/0UAhvGG4TkgDc4G8zraH4KD6Rzm57npoGRpmFui+4ZcH/FxLVY906jkmn6YEEbu4O3CGep3/D9h60WAwSe29lDNyPVRNfnTy+syM9z+vVhwF5jqR3Eor1RuzkKqULPxWb45+KVq0dC/qsCQ9tMTQruWP/VIo0=</ds:Modulus>
<ds:Exponent>AQAB</ds:Exponent>
</ds:RSAKeyValue>
</ds:KeyValue>
</ds:KeyInfo>
</ds:Signature></CFE><ns2:Adenda><data>PGRzQ0ZFIHhtbG5zPSJodHRwOi8vY2ZlLmRnaS5ndWIudXkiPg0KICA8ZGF0b3NBZGVuZGE+DQogICAgPGxleWVuZGFzPg0KICAgICAgPGNvbnN0YW5jaWFJVkE+SVZBIGFsIGTDrWE8L2NvbnN0YW5jaWFJVkE+DQogICAgICA8cmVzb2x1Y2lvbj5SZXMuIDY5NS8yMDE0PC9yZXNvbHVjaW9uPg0KICAgICAgPHZlcmlmaWNhckNvbXByb2JhbnRlPlB1ZWRlIHZlcmlmaWNhciBjb21wcm9iYW50ZSBlbiBodHRwczovL3d3dy5lZmFjdHVyYS5kZ2kuZ3ViLnV5LzwvdmVyaWZpY2FyQ29tcHJvYmFudGU+DQogICAgPC9sZXllbmRhcz4NCiAgICA8ZGF0b3NFeHRyYVJTQT4NCiAgICAgIDxyZWZEb2M+NzY2MDI0NjwvcmVmRG9jPg0KICAgIDwvZGF0b3NFeHRyYVJTQT4NCiAgPC9kYXRvc0FkZW5kYT4NCjwvZHNDRkU+</data></ns2:Adenda></ns2:CFE_Adenda></EnvioCFE_entreEmpresas>
Thanks in advance for any anwser or suggestion