Can you show me how to sign an xml element in C#.
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
Example:
I have this xml file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Signature Id="SignatureIdValue" 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="#idPackageObject" Type="http://www.w3.org/2000/09/xmldsig#Object">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>3H+EGzfJMnudlkWAtFYTfJkaeZM=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>h7ApS9H4NagiJIvt9xUy9FijPVpSQQQtUtvn/hU/WuSPPqap4r3NK98K+qTKptCPTgXcY3P3o+l+vrEXnl71gttfvK3nQabNtPlaXd5KR7fLAJq+6xJNzznLFu7d4JmXDYN3xfq7Scr+vlWcaU5zIGBBbIg90w3AXe1GsYRCpME=</SignatureValue>
<Object Id="idPackageObject">
<Manifest>
<Reference URI="/finder.xml?ContentType=vnd-sizr-datacollection/finder">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>pQAvJzZlmBqHmPU46dj4rYQqjPM=</DigestValue>
</Reference>
<Reference URI="/_rels/finder.xml.rels?ContentType=application/vnd.openxmlformats-package.relationships+xml">
<Transforms>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>Qcp4TAsGEpSIhnVDCYCKih3t+tg=</DigestValue>
</Reference>
<Reference URI="/content.xml?ContentType=vnd-sizr-datacollection/content">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>i8TcHWdSKqLEpMevvhRztwrFCO4=</DigestValue>
</Reference>
<Reference URI="/systemcheck.xml?ContentType=vnd-sizr-datacollection/systemcheck">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>NB1XkMlRU83JUjZqdZLJ0925T54=</DigestValue>
</Reference>
<Reference URI="tree/service.xml?ContentType=vnd-sizr-datacollection/service">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>4FgBGSm/TosmN5bngmTKapOHMSc=</DigestValue>
</Reference>
</Manifest>
<SignatureProperties>
<SignatureProperty Id="idSignatureTime" Target="#SignatureIdValue">
<SignatureTime xmlns="http://schemas.openxmlformats.org/package/2006/digital-signature">
<Format>YYYY-MM-DDThh:mm:ss.sTZD</Format>
<Value>2018-03-25T01:07:44.0+00:00</Value>
</SignatureTime>
</SignatureProperty>
</SignatureProperties>
</Object>
</Signature>
I know how to generate <DigestValue> in <Manifest>, with this code:
private static void SignObject(ref XmlDocument xmlDoc)
{
// Generate a signing key.
RSACryptoServiceProvider Key = new RSACryptoServiceProvider();
// Create a SignedXml object.
SignedXml signedXml = new SignedXml();
// Add the key to the SignedXml document.
signedXml.SigningKey = Key;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
try
{
// Create a new KeyInfo object.
KeyInfo keyInfo = new KeyInfo();
// Load the X509 certificate.
X509Certificate MSCert =
X509Certificate.CreateFromCertFile(Certificate);
// Load the certificate into a KeyInfoX509Data object
// and add it to the KeyInfo object.
keyInfo.AddClause(new KeyInfoX509Data(MSCert));
// Add the KeyInfo object to the SignedXml object.
signedXml.KeyInfo = keyInfo;
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Unable to locate the following file: " +
Certificate);
}
// Compute the signature.
signedXml.ComputeSignature();
// Add the signature branch to the original tree so it is enveloped.
xmlDoc.DocumentElement.AppendChild(signedXml.GetXml());
}
But i don't know how to generate <DigestValue> with <Reference URI="#idPackageObject"...>
Please help me.
Related
I've signed a XML file to send with the proper securities but somehow the service I'm sending detects the file has an invalid signature (X.509 certificate validation it's ok).
I've been searching if it's possible, once I have signed an specific XML, to retrieve the XML signed informations back (like a decryption) to verify if I'm using the right nodes to sign the XML. Could anyone help me?
Ps.: I still have public and private certificate key.
This is the code I used to sign the elements "infEvento" of the XML, and after it, the XML element.
public XmlDocument retornaEvtsXMLAssinados(X509Certificate2 cert, string MensagemXML)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(MensagemXML);
XmlNodeList evtsNode = xmlDoc.GetElementsByTagName("evento");
foreach (XmlElement evtNode in evtsNode)
{
RSACryptoServiceProvider key = new System.Security.Cryptography.RSACryptoServiceProvider();
System.Security.Cryptography.Xml.SignedXml SignedDocument;
var keyInfo = new System.Security.Cryptography.Xml.KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(cert));
key = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
SignedDocument = new System.Security.Cryptography.Xml.SignedXml(evtNode);
SignedDocument.SigningKey = key;
SignedDocument.KeyInfo = keyInfo;
Reference reference = new System.Security.Cryptography.Xml.Reference();
reference.Uri = "#" + evtNode["infEvento"].Attributes["Id"].Value;
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigC14NTransform(false));
SignedDocument.AddReference(reference);
SignedDocument.ComputeSignature();
XmlElement xmlDigitalSignature = SignedDocument.GetXml();
XmlNode nodeAss = xmlDoc.ImportNode(xmlDigitalSignature, true);
evtNode.AppendChild(nodeAss);
}
return xmlDoc;
}
And here is the XML element:
<?xml version="1.0" encoding="utf-8"?>
<envEvento xmlns="http://www.portalfiscal.inf.br/nfe" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" versao="1.00">
<idLote>1</idLote>
<evento versao="1.00">
<infEvento Id="ID2102103518064328381100910655001000067942126336601001">
<cOrgao>91</cOrgao>
<tpAmb>1</tpAmb>
<CNPJ>53773073000182</CNPJ>
<chNFe>35180643283811009106550010000679421263366010</chNFe>
<dhEvento>2018-07-25T02:47:06-03:00</dhEvento>
<tpEvento>210210</tpEvento>
<nSeqEvento>1</nSeqEvento>
<verEvento>1.00</verEvento>
<detEvento versao="1.00">
<descEvento>Ciencia da Operacao</descEvento>
</detEvento>
</infEvento>
<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="#ID2102103518064328381100910655001000067942126336601001">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>BahmhJGVCbcRzzZ2a3IdfoGggSY=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>01MRXk7YiSo9g8OBqR0H4gmYxXBHCFAfoloKacDOYMZr/1Y4kl0GZcfqOCM6+AyxpNmVUYPh860tMklqdTqwXeJR4eceIafJag9lntCD3BuiXnR/O9uP6jxouPu+aGf2fpuVbsOex6WnKG5gPtOnV02cvZ0nB0pMbyhetFEOptq/F8Mv/+wcYsQGnFAFLD2jqqSD0HGeNJPh8C4M6JGh6jjgC8FOnLtihd+cqydNH/OTjDwSczhtEM/3GyeHULf+RJS4DEfRhLLcpdpJAsV9yzSIhkf1ecnVvdjncc4SZdySEOMYhtJLOhQqU6pTGhZS0D0/BiA3O6E6ZTgB1xPUQw==</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MIIH6TCCBdGgAwIBAgIIDsPfGUgZG6UwDQYJKoZIhvcNAQELBQAwcTELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1Cc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Ceaunva2NurlORRiNfhy9YpBqYdIZA5I0S3qOlgi1BLdrNkNHnlAsv7VO3xzEwsX/pR8g7b97TYtjcxJpnz3zeCLJb2Fawudd6C2aubUUxotbj7W/ER1De8yDDHKd7xt62s8Qarw2EICBMQzaGKKnQXBzddtCmS1Skjbloq5s03dH2Q0NJigG7lodRrSWvndtTkmoksL/IjOVq6z4sBYB36mPr+PqMklnisU6pinHa5/vFbJiIfbbNHdcogp+ndOz9AMRS76EtJubspQ/sSALZzicp1bXtgpnaLdOC+ow8pW1XH/bZOcWDo1vieQCs7Y/T2tPIEw4FBa6BvEwbK4w31VUaoe3aac/Wlhl52f7aydp/4VeH5fzFk2sTMpOw5a8tGyO5Avoem1SCJEinjJBLBu9V3UF/4kJc7M4+8i8MdX50cJA30Go5EpMnuvB4nHe8x9RxgpFyBhoqRWkTLBvHCs84OPlu6jMN0whE2Q==</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</evento>
<evento versao="1.00">
<infEvento Id="ID2102103518064328381100910655001000067986126343904601">
<cOrgao>91</cOrgao>
<tpAmb>1</tpAmb>
<CNPJ>53773073000182</CNPJ>
<chNFe>35180643283811009106550010000679861263439046</chNFe>
<dhEvento>2018-07-25T02:47:06-03:00</dhEvento>
<tpEvento>210210</tpEvento>
<nSeqEvento>1</nSeqEvento>
<verEvento>1.00</verEvento>
<detEvento versao="1.00">
<descEvento>Ciencia da Operacao</descEvento>
</detEvento>
</infEvento>
<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="#ID2102103518064328381100910655001000067986126343904601">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>atbTWNxi44DcxulttJidbuNCxQo=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>+wxGkr1l7uFnzlcPFhOSnMN675j9syXlPW9L2UupO1lAienG0GQ9Ta786Wh3/RmqLywfhjob6KXXkh2iiVXAUrOVcQU9akRxwlse93auCEJRff5uQChgKryQycu6XigB/nhNPE50ay8xnhFsSR3nHGYjWcWVnKi6uQAnM69Bx6lOQpvTTh+pSNM2/lXD/eC94b3iKzEi4DkE0yfQ1LRUGd7tUnB0/Y8j+Hu+w8pFYh6Nurabmv1GjNRzpDooZUGxcuWkvtVsFd3VshVqIZ7FKIMnGw8fcsN2h+sv3/OQqe7MJ78z98fMoUv/R1FTklWYqV6vUptK1XnyJ61VbHz1XQ==</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MIIH6TCCBdGgAwIBAgIIDsPfGUgZG6UwDQYJKoZIhvcNAQELBQAwcTELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxNjA0BgNVBAsTLVNlY3JldGFyaWEgZGEgUmVjZWl0YSBGZWRlcmFsIGRvIEJyYXNpbCAtIFJGQjEVMBMGA1UEAxMMQUMgVkFMSUQgUkZCMB4XDTE4MDMwMjIwNDQyNloXDTE5MDMwMjIwNDQyNlowgdkxCzAJBgNVBAYTAkJSMQswCQYDVQQIEwJTUDESMBAGA1UEBxMJU0FPIFBBVUxPMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMTYwNAYDVQQLEy1TZWNyZXRhcmlhIGRhIFJlY2VpdGEgRmVkZXJhbCBkbyBCcmFzaWwgLSBSRkIxFjAUBgNVBAsTDVJGQiBlLUNOUEogQTExFDASBgNVBAsTC0FSIFZBTElEIENEMS4wLAYDVQQDEyVTT0ZUSU5HIEFVVE9NQUNBTyBMVERBOjUzNzczMDczMDAwMTgyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/NdAgCCzmx/vhkgkP8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thanks for the attention
Here is what I currently use for one of mine. Some like adding an additional element may not be needed in your case but, just in case I left it in there.
private static void SignXml(XmlDocument doc, X509Certificate2 cert)
{
var signer = new SignedXmlWithId(doc);
signer.SigningKey = cert.PrivateKey;
signer.KeyInfo = new KeyInfo();
var s = new SecurityTokenReference();
s.Reference = "uuid-639b0-fc-1";
s.ValueType = "http://Something.com";
signer.KeyInfo.AddClause(s);
signer.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
var bodyRef = new Reference("#ID-00008");
var messageRef = new Reference("#ID-00004");
var usernameRef = new Reference("#ID-00001");
bodyRef.AddTransform(new XmlDsigExcC14NTransform());
messageRef.AddTransform(new XmlDsigExcC14NTransform());
usernameRef.AddTransform(new XmlDsigExcC14NTransform());
signer.AddReference(bodyRef);
signer.AddReference(messageRef);
signer.AddReference(usernameRef);
signer.ComputeSignature();
var signData = signer.GetXml();
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("wsee", "http://stuff.to.add");
nsmgr.AddNamespace("cwsh", "http://more.stuff.to.add");
var security = doc.SelectSingleNode("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsee:Security", nsmgr);
security.AppendChild(doc.ImportNode(signData, true));
}
//Subclass to add namespace when signing
public class SignedXmlWithId : SignedXml
{
public SignedXmlWithId(XmlDocument xml) : base(xml)
{
}
public SignedXmlWithId(XmlElement xmlElement) : base(xmlElement)
{
}
public override XmlElement GetIdElement(XmlDocument doc, string id)
{
// check to see if it's a standard ID reference
var idElem = base.GetIdElement(doc, id);
if (idElem == null)
{
var nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("wsu",
"http://wsssecurity.location");
idElem = doc.SelectSingleNode("//*[#wsu:Id=\"" + id + "\"]", nsManager) as XmlElement;
}
return idElem;
}
}
I want to sign a XML with SHA256 by using a self-signed X.509 certificate. I was inspired by many articles in Stackoverflow and use this code:
X509Certificate2 cert = new X509Certificate2();
X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 cert2 in store.Certificates)
{
if (cert2.Subject == "CN=TestCerificate")
{
cert = cert2;
break;
}
}
store.Close();
CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
var exportedKeyMaterial = cert.PrivateKey.ToXmlString(true);
var key = new RSACryptoServiceProvider(new CspParameters(24));
key.PersistKeyInCsp = false;
key.FromXmlString(exportedKeyMaterial);
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("test.xml");
SignedXml signedXml = new SignedXml(doc);
signedXml.SigningKey = key;
signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
Reference reference = new Reference();
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigExcC14NTransform());
reference.Uri = "";
reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
signedXml.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(cert));
signedXml.KeyInfo = keyInfo;
signedXml.ComputeSignature();
doc.Save("testSig.xml");
Afterwards, the generated signed XML part of "testSig.xml" looks like this:
<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#dsa-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>ghOEPeYtAUs5Kb8VMOCIS3f2wIY=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>HANI0GrICbyc5tlmvtU9cB7txdxtuY4uDsntp5XVzaRQbts76ff3Qg==</SignatureValue>
</Signature>
As you can see the XML says that "SHA1" was used to sign the XML instead (see nodes "SignatureMethod" & "DigestMethod"). But I would expect, that the SHA256-URLs have to be stated in these nodes. Is this assumption correct? If yes, does anybody know how to solve this problem? I use C# 4.6.0.
With best regards,
Michael
While you successfully called signedXml.ComputeSignature() that just does the computation, it doesn't insert a signature element into the document (the XmlDocument you pass in the constructor is just what document GetXml()'s node will parent to).
You need to call signedXml.GetXml() (after ComputeSignature) to get the computed ds:Signature element, then insert that into your document.
The fact that your document has a signature node already in it is confusing. My first thought was that test.xml already had that signature in it, but your comment says that it was just some oops code from elsewhere. Lesson learned, I guess :).
I need to sign a XML file with a private RSA key to be verified with my C# application. When I sign the xml with my C# application, this is the final output:
<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>VIRRzqwb20aCSXrRTX1Y5vW//IA=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>mS3JQ/KmyXCayLly4hHRXKM51jPy230B3h4ngjzOhq0xR/7BRDQP2wfp7ugVcL5kMWaV+pBHbJgdvvu8OrzyxCUQ+R7RYqWpEBYJHUARov0Pws7oFybFpmzRnwhg2gPaPEzcVpK4VL4G1iM07XgmoSKM8Id0fRQ1lD+4BEcAxNY=</SignatureValue>
</Signature>
Signing in C#:
public static void SignXmlDocument(RSA key, XmlDocument doc)
{
var sxml = new SignedXml(doc);
sxml.SigningKey = key;
sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
var r = new Reference("");
r.AddTransform(new XmlDsigEnvelopedSignatureTransform(false));
sxml.AddReference(r);
sxml.ComputeSignature();
var sig = sxml.GetXml();
doc.DocumentElement.AppendChild(sig);
}
How can I make the same in PHP?
You can use XMLDsig
Install the library and register the paths in your autoloader. If you use composer both steps are automatic.
require_once __DIR__ . '/vendor/autoload.php';
$xmlDocument = new DOMDocument();
$xmlDocument..... // define the contents to sign
$xmlTool = new FR3D\XmlDSig\Adapter\XmlseclibsAdapter();
$xmlTool->setPrivateKey(file_get_contents('<path to your private key>/private.pem');
$xmlTool->addTransform(FR3D\XmlDSig\Adapter\XmlseclibsAdapter::ENVELOPED);
$xmlTool->sign($xmlDocument);
Now $xmlDocument has the <signature> element at the end.
I have problem with XmlDsigC14NTransform. I trying to repeat example from
http://www.di-mgt.com.au/xmldsig2.html (part Compose the canonicalized SignedInfo element and compute its SignatureValue)
but my code loses whitespaces from xml and i cant get correct hexdump.
My C# code:
XmlDocument signedInfoXml = new XmlDocument();
signedInfoXml.Load(#"C:\temp\new_sign.txt");
XmlDsigC14NTransform xmlTransform = new XmlDsigC14NTransform();
xmlTransform.LoadInput(signedInfoXml);
MemoryStream memoryStream = (MemoryStream)xmlTransform.GetOutput();
return BitConverter.ToString(memoryStream.ToArray()).Replace("-"," ");
Source Xml(from file C:\temp\new_sign.txt):
<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<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>UWuYTYug10J1k5hKfonxthgrAR8=</DigestValue>
</Reference>
</SignedInfo>
How i can save whitespaces into my xml and get canonicalized xml like in sample (http://www.di-mgt.com.au/xmldsig2.html)?
You can set a flag on the XMLDocument:
// Create a new XML document.
XmlDocument xmlDocument = new XmlDocument();
// Format using white spaces.
xmlDocument.PreserveWhitespace = true;
// Load the XML file into the document.
xmlDocument.Load("file.xml");
Log OUTPUT
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.DOMXMLSignature validate
FINE: Reference[#uuid-26810b23-330b-49c0-af30-59c2a8211341-1] is valid: true
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.DOMReference dereference
FINE: URIDereferencer class name: org.jcp.xml.dsig.internal.dom.DOMURIDereferencer
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.DOMReference dereference
FINE: Data class name: org.jcp.xml.dsig.internal.dom.ApacheNodeSetData
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.ApacheCanonicalizer transform
FINE: Created transform for algorithm: http://www.w3.org/2001/10/xml-exc-c14n#
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.ApacheCanonicalizer transform
FINE: ApacheData = true
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.DOMReference validate
FINE: Expected digest: q9/MlLVrhvl21tGGmxuBVh1V4Mc=
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.DOMReference validate
FINE: Actual digest: bFCOsfjajqOmn3mWNcMw+HRtyPM=
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.DOMXMLSignature validate
**FINE: Reference[#e23c17af-c76f-4aaf-bc28-33c5261a253d] is valid: false
25/05/2012 2:08:57 PM org.jcp.xml.dsig.internal.dom.DOMXMLSignature validate
FINE: Couldn't validate the References**
org.apache.ws.security.WSSecurityException: The signature or decryption was invalid
at org.apache.ws.security.processor.SignatureProcessor.verifyXMLSignature(SignatureProcessor.java:393)
at org.apache.ws.security.processor.SignatureProcessor.handleToken(SignatureProcessor.java:188)
at org.apache.ws.security.WSSecurityEngine.processSecurityHeader(WSSecurityEngine.java:396)
at org.apache.ws.security.WSSecurityEngine.processSecurityHeader(WSSecurityEngine.java:304)
at org.apache.ws.security.WSSecurityEngine.processSecurityHeader(WSSecurityEngine.java:249)
at org.apache.ws.security.WSSecurityEngine.processSecurityHeader(WSSecurityEngine.java:203)
at au.gov.mca.uhi.security.dsig.XWSSDigitalSignatureProcessorTest.testVerifyWithWSS4J(XWSSDigitalSignatureProcessorTest.java:355)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:44)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
SOAP Security Token
<o:Security s:mustUnderstand="1"
xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<u:Timestamp u:Id="uuid-26810b23-330b-49c0-af30-59c2a8211341-1">
<u:Created>2012-05-25T03:58:21.289Z</u:Created>
<u:Expires>2012-05-25T04:03:21.289Z</u:Expires>
</u:Timestamp>
<o:BinarySecurityToken u:Id="uuid-bf155ac7-0ca3-459f-acb5-d8acf3a882d4-2"
ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">MIIF1zCCBL+gAwIBAgIDBHONMA0GCSqGSIb3DQEBBQUAMH8xCzAJBgNVBAYTAkFVMQwwCgYDVQQKEwNHT1YxGzAZBgNVBAsTEk1lZGljYXJlIEF1c3RyYWxpYTFFMEMGA1UEAxM8VGVzdCBNZWRpY2FyZSBBdXN0cmFsaWEgT3JnYW5pc2F0aW9uIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTExMDkyMDA2MzkwMFoXDTE2MDgxNDA1NDMwOFowgZExCzAJBgNVBAYTAkFVMQwwCgYDVQQIEwNBQ1QxFDASBgNVBAcTC1RVR0dFUkFOT05HMRowGAYDVQQKExFUZXN0IExvY2F0aW9uIDAyNzEaMBgGA1UECxMRVGVzdCBMb2NhdGlvbiAwMjcxJjAkBgNVBAMTHVRlc3QgTG9jYXRpb24gMDI3IDo1NjU3MDUwMDkxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzEdwMFSGslbPo9jTWar8g1pEf+Y3/ppErJUyr92JYqWlIxIU2iHpsx/xKi8wiPgn6ZDrWmULqXaI7xTwjBlaYvBuz7CJ3rfXXk74Fx4VnoGBqxnMiE4ineaxEc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LFrlwOWdkWHFL/9/zmZlFuBNhpZPgYcXpLjC1S3cA5btWAFwMYMBa8igWsvjhFyjjKYhxMlYgnJzKQx2sc6pUXuId2qhGhikWmgzT+Wdy6soP8FKJPLSwBlkTUVq8ep+yIfBx3tYfnK79n/+FX1bz52/nFZmnpZwkEhTB8f9y/GuyzO/pt0F9bel4txZPj36XIHF0k/9SuzpLzwkmAy+89tWu0L4+0J8CLkgfiGprPKW6HByJZWmZyAqs9UIOy2FXnL/CdozZKXnxmEIgTCkcPgSs0olm/A/Wfv4wdsPrNWMmqGL73AoSfM2wgHmQ9k4mPU=</o:BinarySecurityToken>
<wsse:UsernameToken wsu:Id="e23c17af-c76f-4aaf-bc28-33c5261a253d"
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">
<wsse:Username>user1</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">icnriCyW09WOpQABOeQqFEiqxwY=</wsse:Password>
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">wbwf0IRtQBA6fsrmpQd8fA==</wsse:Nonce>
<wsu:Created>2012-05-25T13:58:21Z</wsu:Created>
</wsse:UsernameToken>
<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/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#_1">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>8Po0d4s3JJB1Xh4vdB6+7M/ivoA=</DigestValue>
</Reference>
<Reference URI="#_2">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>Azl0elmnUzxTSLUuwfWf6DLT8h8=</DigestValue>
</Reference>
<Reference URI="#_3">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>h1iD7HzEK+uslbPRHjwN2zt7zhc=</DigestValue>
</Reference>
<Reference URI="#_4">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>WZ3YS9m3NBoROTnEKUEJ/bNmMDw=</DigestValue>
</Reference>
<Reference URI="#_5">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>k69pykploFPkXhw5ogDHcjcJUI0=</DigestValue>
</Reference>
<Reference URI="#_6">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>TSr1cnqSoYmoEIURjA5OZB/iyS0=</DigestValue>
</Reference>
<Reference URI="#uuid-26810b23-330b-49c0-af30-59c2a8211341-1">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>wSsjhUgRFAN3by438s7ZvGSSgCw=</DigestValue>
</Reference>
<Reference URI="#e23c17af-c76f-4aaf-bc28-33c5261a253d">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>q9/MlLVrhvl21tGGmxuBVh1V4Mc=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>t/piYSnEwCIzqMxC0LQs9fxUla2BKA0GkMI4oLLqZdkthCo9LNvxJP8Luf1d91CEETZ5B4FsQI7QtcA+qHya78K5s+mzn8/2zhEGzAYxkaLeDCUvrad10Mlqssh5AhLbxonZ4/7mDs1v5+s7EVqM0tjpc0tHK0vmroNz0qnAxjCZqEEYpK3/uJ4iwO86khk5pQwqArrwUAqV26/8sXi6c5CfoZcGaVzjIKSAuc+ybV0O42c5OECMe+9G5ZJAkRkw+korLSKgeslLZa18+g/x7WMeUmbo9wiPLuT5kdvIkGRpPN22CQYeSblTFly26J5LIaPdZFSBIAOT3bYs6G4bxA==</SignatureValue>
<KeyInfo>
<o:SecurityTokenReference>
<o:Reference URI="#uuid-bf155ac7-0ca3-459f-acb5-d8acf3a882d4-2"/>
</o:SecurityTokenReference>
</KeyInfo>
</Signature>
</o:Security>
<SignatureValue>t/piYSnEwCIzqMxC0LQs9fxUla2BKA0GkMI4oLLqZdkthCo9LNvxJP8Luf1d91CEETZ5B4FsQI7QtcA+qHya78K5s+mzn8/2zhEGzAYxkaLeDCUvrad10Mlqssh5AhLbxonZ4/7mDs1v5+s7EVqM0tjpc0tHK0vmroNz0qnAxjCZqEEYpK3/uJ4iwO86khk5pQwqArrwUAqV26/8sXi6c5CfoZcGaVzjIKSAuc+ybV0O42c5OECMe+9G5ZJAkRkw+korLSKgeslLZa18+g/x7WMeUmbo9wiPLuT5kdvIkGRpPN22CQYeSblTFly26J5LIaPdZFSBIAOT3bYs6G4bxA==</SignatureValue>
<KeyInfo>
<o:SecurityTokenReference>
<o:Reference URI="#uuid-bf155ac7-0ca3-459f-acb5-d8acf3a882d4-2"/>
</o:SecurityTokenReference>
</KeyInfo>
</Signature>
</o:Security>
I have tried almost everything I could i have used inspector and encoder to do this but so far no luck, any help will be appreciated. Please
Current Code:
AsymmetricSecurityBindingElement securityBindingElement = new AsymmetricSecurityBindingElement();
securityBindingElement.EndpointSupportingTokenParameters.Signed.Add(new UsernameTokenParameters());
X509SecurityTokenParameters initiator
= new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial,
SecurityTokenInclusionMode.AlwaysToRecipient);
initiator.RequireDerivedKeys = false;
initiator.ReferenceStyle = SecurityTokenReferenceStyle.Internal;
securityBindingElement.InitiatorTokenParameters = initiator;
X509SecurityTokenParameters recipient
= new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial,
SecurityTokenInclusionMode.AlwaysToInitiator);
recipient.RequireDerivedKeys = false;
securityBindingElement.RecipientTokenParameters = initiator;
securityBindingElement.SetKeyDerivation(false);
securityBindingElement.IncludeTimestamp = true;
securityBindingElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic128;
securityBindingElement.MessageSecurityVersion = MessageSecurityVersion
.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
X509SecurityTokenParameters tokenParameters = new X509SecurityTokenParameters();
tokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
tokenParameters.RequireDerivedKeys = false;
securityBindingElement.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
CustomBinding binding = new CustomBinding();
binding.Elements.Add(securityBindingElement);
binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8));
//binding.Elements.Add(new CustomEncoderBindingElement());
binding.Elements.Add(httpBindingElement);
EndpointAddress serviceAddress = new EndpointAddress(new Uri("http://xya.com"),
EndpointIdentity.CreateDnsIdentity(
"Test Location 027 :5657050091"),
new AddressHeaderCollection());
ChannelFactory<DhsUserAuthUploadHposDvaStatementsPortTypeChannel> channelFactory =
new ChannelFactory<DhsUserAuthUploadHposDvaStatementsPortTypeChannel>(binding, serviceAddress);
UsernameClientCredentials credentials = new UsernameClientCredentials(new UsernameInfo("user1", "user1"));
credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint,
"6c1a76f952028e092cea367d40d6cf5833d9d3a3");
credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.CurrentUser, StoreName.TrustedPeople,
X509FindType.FindByThumbprint,
"6c1a76f952028e092cea367d40d6cf5833d9d3a3");
channelFactory.Endpoint.Behaviors.Remove(typeof(ClientCredentials));
channelFactory.Endpoint.Behaviors.Add(credentials);
var client = channelFactory.CreateChannel();
client.upload();
I have tried almost everything I could i have used inspector and encoder to do this but so far no luck, any help will be appreciated.
The challenge here is that you need a username token with message digest + created + nonce AND you need it signed. If you have any way to dismiss one of this requirements it will be easier. Otherwise here is a direction, it will require some work.
check out this project. it is your friend to help you create the username token in the requested format.
In order to create the security binding element use
SecurityBindingElement.CreateMutualCertificateBindingElement()
then as you did above add to it the user name token (the one form item #1).
note you will be required to sepcify a service certificate. you probably don't have or need one, so just supply any dummy certificate in the service credentials property, it can even be the same one as the client certificate.
If you have not done so already decorate your contracts (reference.cs?) with:
[ServiceContract(ProtectionLevel = ProtectionLevel.Sign)]
since (as it seems from the partial soap envelope) you only use signature and not encryption.