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>MIIH6TCCBdGgAwIBAgIIDsPfGUgZG6UwDQYJKoZIhvcNAQELBQAwcTELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxNjA0BgNVBAsTLVNlY3JldGFyaWEgZGEgUm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rNkNHnlAsv7VO3xzEwsX/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>atbTWNxi44DcxulttJid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EB/wQEAwIF4DAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwgaYGA1UdEQSBnjCBm4EVdGVyZXphQHNvZnRpbmcuY29tLmJyoDgGBWBMAQMEoC8ELTIxMTAxOTUyODc0ODY0MzE4MTUwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMKAUBgVgTAEDAqALBAlUSU5HIFlBTkegGQYFYEwBAwOgEAQONTM3NzMwNzMwMDAxODKgFwYFYEwBAwegDgQMMDAwMDAwMDAwMDAwMA0GCSqGSIb3DQEBCwUAA4ICAQAz9zGz3gT09rIOmkKTF1ZnRt2oGeedEnlqrJ7lqV9vu3xjyzEQoFyqmp2u93YeMuTOi7hjeZ0BYaPnNJbOlJ2I4sJwioJc/PsAqn+VDbb7KVrUC6VXZVYs/9tsFETrNdal7BnGXts5wiZtPa1iRx90RLxFfJeJ0E2Y/0kY4VCagn+vovgyYB76i8F03lkJnW2ScpCeaunva2NurlORRiNfhy9YpBqYdIZA5I0S3qOlgi1BLdrNkNHnlAsv7VO3xzEwsX/pR8g7b97TYtjcxJpnz3zeCLJb2Fawudd6C2aubUUxotbj7W/ER1De8yDDHKd7xt62s8Qarw2EICBMQzaGKKnQXBzddtCmS1Skjbloq5s03dH2Q0NJigG7lodRrSWvndtTkmoksL/IjOVq6z4sBYB36mPr+PqMklnisU6pinHa5/vFbJiIfbbNHdcogp+ndOz9AMRS76EtJubspQ/sSALZzicp1bXtgpnaLdOC+ow8pW1XH/bZOcWDo1vieQCs7Y/T2tPIEw4FBa6BvEwbK4w31VUaoe3aac/Wlhl52f7aydp/4VeH5fzFk2sTMpOw5a8tGyO5Avoem1SCJEinjJBLBu9V3UF/4kJc7M4+8i8MdX50cJA30Go5EpMnuvB4nHe8x9RxgpFyBhoqRWkTLBvHCs84OPlu6jMN0whE2Q==</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</evento>
</envEvento>
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;
}
}
Related
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.
So I'm trying to create a saml2 response using C# with .net 4.5 System.IdentityModel.Tokens.Saml2Assertion class.
So far, I have created an assertion xml, but the sample I'm looking at here https://www.samltool.com/generic_sso_res.php has some response tags at the beginning. My first question is how do I get the response porition of that added to my assertion? (I'll post code below). My second question is that sample has tags like
Saml2NameIdentifier identifier = new Saml2NameIdentifier("myid.com");
Saml2Assertion assert = new Saml2Assertion(identifier);
assert.Subject = new Saml2Subject(identifier);
string attrNamespace = "http://id.certmetrics.com/";
Saml2AttributeStatement attrs = new Saml2AttributeStatement();
DataRow row = qGetCanData.SqlExecDataTable(null, SelectedCandidate.CmcID).Rows[0];
//we have a list of key value pairs in the json string that give us an attribute name, and a column name. The column
//name is what value we would get from the data row using the eval string function
foreach (KeyValuePair<string, string> item in cset.Attributes)
{
string val = EvalString(row, item.Value, string.Empty);
if (!string.IsNullOrEmpty(val))
{
Saml2Attribute attr = new Saml2Attribute(item.Key);
attr.Values.Add(val);
attrs.Attributes.Add(attr);
}
}
assert.Statements.Add(attrs);
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings() { OmitXmlDeclaration = true, Encoding = Encoding.UTF8 };
// Use this line to get a .p12 file into the Hex format. Then copy/paste the Hex into a string to store it in the source code.
//string sslCertBytesInHex = Utility.BytesToHex(File.ReadAllBytes(Server.MapPath("~/app_data/ssl.p12")));
string sslCertBytesInHex = "ABigLongHexHere";
// This will load the cert just fine. By using "MachineKeySet", we avoid the need to use "Load User Profile"=true in the AppPool.
X509Certificate2 clientCert = new X509Certificate2();
clientCert.Import(Utility.HexToBytes(sslCertBytesInHex), "1234", X509KeyStorageFlags.MachineKeySet);
X509SigningCredentials creds = new X509SigningCredentials(clientCert);
assert.SigningCredentials = creds;
Saml2SecurityToken token = new Saml2SecurityToken(assert);
StringWriter sw = new StringWriter();
Saml2SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler();
tokenHandler.WriteToken(new XmlTextWriter(sw), token);
//here is where I don't know how to get that "response" tags porition, plus add in the saml: to all the tags
The XML it generates looks like this
<Assertion ID="_6d1bd525-b460-42a7-9def-fe28d26f5713" IssueInstant="2017-06-14T12:54:28.141Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
<Issuer>myid.com</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="#_6d1bd525-b460-42a7-9def-fe28d26f5713">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<DigestValue>SomeString</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>TheSigValue</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>TheCertValue</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
<Subject>
<NameID>myid.com</NameID>
</Subject>
<AttributeStatement>
<Attribute Name="att1">
<AttributeValue>att1</AttributeValue>
</Attribute>
</AttributeStatement>
</Assertion>
The .NET Framework support for SAML2 is only for SAML2 Tokens - which is an <Assertion> in XML. To generate the <Response> XML you need something supporting the SAML2 Protocol. Either build it yourself or use an existing library. The one I've made that is open source is Kentor.AuthServices, but there are also other options both, open source and commercial.
Hi I am new to SAML and SSO techniques. I am trying to create a valid SAML reponse with signed and encrypted Assertion. I have created a SAML response which is signed but i am not able to encrypte the assertion and create the tag. My Generated SAML response is,
<samlp:Response xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_88a4cf19-6f41-46ee-9dc3-98ac80168bd9" Version="2.0" IssueInstant="2015-03-26T11:43:13.4468624Z" Destination="Test1" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<saml:Issuer>Test</saml:Issuer>
<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="#_49bc8835-7c9a-4ee2-8087-7cfcbe48375f">
<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>My4iQVO1Oy3i6jV+Jlp0czX0mpA=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>GWfdKMCHbiqq6OhyHQ0y2LoDQkmC95fs3SKWyPMzu6jSjbf6vrMRFCrlch+DU1k3+sfsj1tFkJNMPKpxZIx2XksjnEQv3Hdqy7oPSoGiODmrky7CTKEdYbCQqu6a8dwNBLNQTClYAgDz/m5yfbFlJNPy9TtsCl2l1R/qg6dzVkA=</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MIIBwTCCAS6gAwIBAgIQr71oSHfrBKpKpRUTWmBFCzAJBgUrDgMCHQUAMCMxITAfBgNVBAMeGABCAEYASQBcAGQAcwBwAGUAaQBnAGgAdDAeFw0xMDAyMTkxMzI4MzlaFw0xMTAyMTkxOTI4MzlaMCMxITAfBgNVBAMeGABCAEYASQBcAGQAcwBwAGUAaQBnAGgAdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAxXmIj8FBaL+94B/fNsBcoNZZraicGsm5+8VtWQIaGdM65q6vgDSQAg4zOkTQCqKh2vlN2NHSZb2XjcrUTWm2Vb279dvkOZfZ1mdQeLjM2LbXvrY4e7qK1dhZy9gZ3Mhvuk3cKPwwPsLNFifOt6OsS8ZzK7/PC+uUKznZtRsCAwEAATAJBgUrDgMCHQUAA4GBADGP1MjZm28GdYy3mQGprHQNDn8fIyBQvhwVwl4SVPxYDTKG7OsUC/QDUzy8vGXm+9qd2Es5creZS1DTAweC60JsJLdmp631FnbG4xJOCRHbR0HWyruhGkN6wPJ0RyJbdUrAcEPG4cfcYwl3oBeL48MfUD56UC0jSfBezUvnOMBX</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="_49bc8835-7c9a-4ee2-8087-7cfcbe48375f" IssueInstant="2015-03-26T11:43:13.6835615Z">
<saml:Issuer>Test</saml:Issuer>
<saml:Subject>
<saml:NameID NameQualifier="TestDomain">TestSubject</saml:NameID>
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData NotOnOrAfter="2015-03-26T11:48:13.7304370Z" Recipient="Test1" />
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2015-03-26T11:43:13.6835615Z" NotOnOrAfter="2015-03-26T11:48:13.6835615Z">
<saml:AudienceRestriction>
<saml:Audience>TestDomain</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2015-03-26T11:43:13.6835615Z">
<saml:AuthnContext>
<saml:AuthnContextClassRef>AuthnContextClassRef</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
<saml:AttributeStatement>
<saml:Attribute Name="UserId" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
<saml:AttributeValue xmlns:q1="http://www.w3.org/2001/XMLSchema" p7:type="q1:string" xmlns:p7="http://www.w3.org/2001/XMLSchema-instance">1000001</saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="UserName" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
<saml:AttributeValue xmlns:q2="http://www.w3.org/2001/XMLSchema" p7:type="q2:string" xmlns:p7="http://www.w3.org/2001/XMLSchema-instance">Manish Pandey</saml:AttributeValue>
</saml:Attribute>
</saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>
Can any one suggest any method to accomplish this?
it depends what kind of encryption you want to use... Basically you would have to encrypt signed assertion and replace assertion node with EncryptedAssertion node.
I recommend using both symmetric and asymmetric encryption.
Using Symmetric key to encrypt the whole of assertion node and then use asymmetric (i.e. certificate public/private key to encrypt symmetric key). I have used our client's certificate public key to encrypt symmetric key so only they can decrypt using their private key.
I have also specified certificate I want to use in web.config...
string samlResponseXml = '<SAML Response Message>'
XmlDocument loginResponseXmlDocument = new XmlDocument();
loginResponseXmlDocument.LoadXml(samlResponseXml);
// Add name spaces
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(loginResponseXmlDocument.NameTable);
namespaceManager.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
namespaceManager.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
namespaceManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
namespaceManager.AddNamespace("xenc", "http://www.w3.org/2001/04/xmlenc#");
Encrypt(loginResponseXmlDocument, namespaceManager);
private void Encrypt(XmlDocument document, XmlNamespaceManager namespaceManager)
{
// create symmetric key
var key = new RijndaelManaged();
key.BlockSize = 128;
key.KeySize = 256;
key.Padding = PaddingMode.ISO10126;
key.Mode = CipherMode.CBC;
XmlElement assertion = (XmlElement)document.SelectSingleNode("/samlp:Response/saml:Assertion", namespaceManager);
EncryptedXml eXml = new EncryptedXml();
byte[] encryptedElement = eXml.EncryptData(assertion, key, false);
EncryptedData edElement = new EncryptedData
{
Type = EncryptedXml.XmlEncAES256Url
};
const string encryptionMethod = EncryptedXml.XmlEncAES256Url;
edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);
edElement.CipherData.CipherValue = encryptedElement;
// edElement = EncryptedData
// Now encrypt symmetric key
string certificateDn = ConfigurationManager.AppSettings["CertificateDN"];
X509Certificate2 x509Certificate = GetCertificate(certificateDn);
RSACryptoServiceProvider rsa = x509Certificate.PublicKey.Key as RSACryptoServiceProvider;
byte[] cryptedData = rsa.Encrypt(key.Key, false);
//string data = Convert.ToBase64String(cryptedData);
//byte[] encryptedKey = EncryptedXml.EncryptKey(key.Key, rsa, true);
EncryptedKey ek = new EncryptedKey();
ek.CipherData = new CipherData(cryptedData);
ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
//EncryptedData edkey = new EncryptedData();
//string data1 = Convert.ToBase64String(encryptedKey);
//edkey.CipherData.CipherValue = System.Text.Encoding.Unicode.GetBytes(data);
rsa.Clear();
XmlDocument encryptedAssertion = new XmlDocument();
// Add name spaces
XmlDeclaration xmlDeclaration = encryptedAssertion.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement encryptedRoot = encryptedAssertion.DocumentElement;
encryptedAssertion.InsertBefore(xmlDeclaration, encryptedRoot);
XmlElement encryptedAssertionElement = encryptedAssertion.CreateElement("saml", "EncryptedAssertion", "urn:oasis:names:tc:SAML:2.0:assertion");
encryptedAssertion.AppendChild(encryptedAssertionElement);
string xml = edElement.GetXml().OuterXml;
XmlElement element = AddPrefix(xml, "xenc", "http://www.w3.org/2001/04/xmlenc#");
var encryptedDataNode = encryptedAssertion.ImportNode(element, true);
encryptedAssertionElement.AppendChild(encryptedDataNode);
xml = ek.GetXml().OuterXml;
element = AddPrefix(xml, "xenc", "http://www.w3.org/2001/04/xmlenc#");
var encryptedKeyNode = encryptedAssertion.ImportNode(element, true);
encryptedAssertionElement.AppendChild(encryptedKeyNode);
var root = document.DocumentElement;
var node = root.OwnerDocument.ImportNode(encryptedAssertionElement, true);
root.RemoveChild(assertion);
root.AppendChild(node);
}
Once assertion is encrypted.. this is what it will look like:
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Destination="https://aviva-rpt.distribution-technology.com" ID="_fba2f5af-a430-8001-5cb8-9714f3aeb4bc"
IssueInstant="2015-02-04T16:32:33.446Z" Version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://www.client.sds</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
<saml:EncryptedAssertion>
<xenc:EncryptedData>
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/>
<xenc:CipherData>
<xenc:CipherValue>zjAgkZ=</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedData>
<xenc:EncryptedKey>
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
<xenc:CipherData>
<xenc:CipherValue>DyA22==</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedKey>
</saml:EncryptedAssertion>
</samlp:Response>
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");