We have a tool that is not in .net and it decrypts a SAML xml request, I 'm trying to replicate the behavior in .net, however, I'm not sure the correct way to do it, I see the X509 and cipher in the xml body, using that I need to decrypt it??
SAML XML Body
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://uat.com/" ID="_fee80033-e30f-4104-a149-a0387a751b50" IssueInstant="2022-11-04T06:12:39.266Z" Version="2.0">
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">TEST:SAML2.0:DEV</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/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod>
<ds:Reference URI="#_fee80033-e30f-4104-a149-a0387a751b50">
<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/2000/09/xmldsig#sha1"></ds:DigestMethod>
<ds:DigestValue>JQfbd3hmIoYA0GiKQnS/iWLOZMk=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>ZVlFqS+BHn5jPvyLgf3k0G6/p9l52jLTivNpJsfn9IaTqyVxo8R+PeH59yxeR58XoYybtjn2FXlv
tB66sJUIdwJRAAFQQxBVsG8eLmDF23rVAr1VXVVeisKhs/A4NlJ+1hirilxhXIeV8ig16hjiTylC
vnVAyGGWMAcBCUFlrL9X9I2dkRgiZTQvjtFBJ4QBM+5lSoy8nho8hOvwNL2Oj4LemQWIoAuc65rI
pZbaA0IXRT8x5iedFca7N/xJVCiaIZh5SobGRB8iIXh0kDdKNUNyyaxxvQCEFt+JDnGwSCKvgHDb
HImEqNmMgcMuSgE9P3zffFDr4Rw+6VKN5KuIYw==</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate>certificatekey</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</ds:Signature>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"></samlp:StatusCode>
</samlp:Status>
<saml:EncryptedAssertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Type="http://www.w3.org/2001/04/xmlenc#Element">
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"></xenc:EncryptionMethod>
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<xenc:EncryptedKey>
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"></xenc:EncryptionMethod>
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<X509Data>
<X509Certificate>certificatekey</X509Certificate>
</X509Data>
</KeyInfo>
<xenc:CipherData>
<xenc:CipherValue>cipherValue</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedKey>
</ds:KeyInfo>
<xenc:CipherData>
<xenc:CipherValue>cipherValue</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedData>
</saml:EncryptedAssertion>
</samlp:Response>
I'm not sure whether the below code is correct for me.
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
XmlDocument doc = new XmlDocument();
doc.Load("/Data/SAML.xml");
Decrypt(doc);
public static void Decrypt(XmlDocument Doc)
{
// Check the arguments.
if (Doc == null)
throw new ArgumentNullException("Doc");
// Create a new EncryptedXml object.
EncryptedXml exml = new EncryptedXml(Doc);
var cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_ENC_RSA_KEY";
var rsaKey = new RSACryptoServiceProvider(cspParams);
// Decrypt the XML document.
exml.AddKeyNameMapping("rsaKey", rsaKey);
exml.DecryptDocument();
}
Related
Verify digital signature on xml in .net core using RSA, below code is returning always false.
Have tried the below solutions but results are same.
SignedXml.CheckSignature fails in .NET 4 but it works in .NET 3.5, 3 or 2
SignedXml checksignature returns false
Adding XML & C# code
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:car="http://www.absd.com/cargoport"
>
<soapenv:Header>
<wsse:Security
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
>
<ds:Signature Id="SIG-A2ACE59D81846C2E1416732798666315"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
>
<ds:SignedInfo
xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces PrefixList="car soapenv"
xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"
/>
</ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<ds:Reference URI="">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces PrefixList="car"
xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"
/>
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<ds:DigestValue>aiO7Q1GM4NbMtl/FYw8WRpdOjc0=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>l8xd8HWSj+UbuOMsEg9rrBn54hDxFh76Vef/C8+sHQ5Gv7ab6Km50iMcVMCGsXqCRqTvsnjXCrFg YJkSw3N5yJ61qJ4doE7dvBBjwUgIG/wIg89KI7KFnyJu5FOEJBtDk03j49hVXu90kYV1cgLmlIqg yjItkhMHttZ71XGkFcat9ZWfczrQQ9dR3b1ZtSA8lRtsl9hSTgNWzItZUBI2iwxa53i+Xg2up6IO pdXersRf10o0BhB9K6UZ8yUeMVKpXwhM1AIwxM2fn4tC+ZV0b2HLf0KHAS7KdBI8w7cAv7yIYFJH D+GhgKgF8J74SAJWEg5c0g4KLIUPhJlNa/Hx9g==</ds:SignatureValue>
<ds:KeyInfo Id="KI-A2ACE59D81846C2E1416732798666002">
<wsse:SecurityTokenReference wsu:Id="STR-A2ACE59D81846C2E1416732798666043">
<wsse:KeyIdentifier 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/oasis-wss-soap-message-security-1.1#ThumbprintSHA1">+8kGrRMHE4iTqmjaaTjpjQP/W4g=</wsse:KeyIdentifier>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
</wsse:Security>
</soapenv:Header>
<soapenv:Body wsu:Id="id-A2ACE59D81846C2E1416732798666074"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
>
<region>usa</region>
</soapenv:Body>
</soapenv:Envelope>
C# code
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = true;
xmlDocument.Load("TestSample8.xml");
XmlNodeList signatureNodeList = xmlDocument.GetElementsByTagName("ds:Signature");
var signedXml = new SignedXml(xmlDocument);
// double-check the schema
// usually we would validate using XPath
var signatureElement = xmlDocument.GetElementsByTagName("ds:Signature");
if (signatureElement.Count != 1)
throw new InvalidOperationException("Too many signatures!");
signedXml.LoadXml((XmlElement)signatureElement[0]);
// validate references here!
if ((signedXml.SignedInfo.References[0] as Reference)?.Uri != "")
throw new InvalidOperationException("Check your references!");
X509Certificate2 x509Certificate2 = new X509Certificate2("example.crt");
// Verify the signature, assume the public key part of the
var result = signedXml.CheckSignature();
// signing key is in the key variable
if (signedXml.CheckSignature(x509Certificate2.GetRSAPublicKey()))
Console.WriteLine("Signature verified");
else
Console.WriteLine("Signature not valid");
I have the following requirements from a 3rd party service that I'm using
Transactions dealing with personal information and other sensitive
data use transport layer security protection. The web service message
will be transported over https (HTTP over SSL) and must adhere to Web
Service (WS)-Security v1.1 standard. The WS-Security section of the
service message must:
Be signed with x.509 certificate using a 2048 bit key size
Use SHA2 with RSA algorithm for encryption
Use C14 canonicalization.
I managed to get my message signed with the following code
someServiceRef.widjetClient client = null;
try
{
X509Certificate2 signingCert = GetSigningCert();
var bindings = new BasicHttpsBinding();
bindings.Security.Mode = BasicHttpsSecurityMode.TransportWithMessageCredential;
bindings.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
client = new someServiceRef.widjetClient(
bindings,
new EndpointAddress(#"<URL OF SERVICE>"));
client.ClientCredentials.ClientCertificate.Certificate = signingCert;
client.ClientCredentials.ServiceCertificate.DefaultCertificate = signingCert;
client.Open();
var request = BuildRequest();
var response = client.SayHello(request);
Console.WriteLine(response);
}
finally
{
if (client != null)
{
if (client.State == System.ServiceModel.CommunicationState.Faulted)
client.Abort();
else
client.Close();
}
}
The problem is that my message is being signed with sha1 instead of sha2. I'm trying to sign my message properly but the examples I found online have you generate the soap message then manually modify it with XML parsing and adding new nodes. I don't understand these examples and I'm trying to figure out a way to tell the service to do it for me. I have a sample of what the request signature should look like from the 3rd party below. I don't see anything in the client or binding class that would allow me to change things like the signature algorithm. How would I go about doing this?
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" SOAP-ENV:mustUnderstand="1">
<wsse:BinarySecurityToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" 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="XWSSGID-12324774331131695995061">XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</wsse:BinarySecurityToken>
<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/2000/09/xmldsig#rsa-sha2" />
<ds:Reference URI="#XWSSGID-1232477437326-1352495766">
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha2" />
<ds:DigestValue>XXXXXXXXXXXXXXXXXXXXXX</ds:DigestValue>
</ds:Reference>
<ds:Reference URI="#XWSSGID-1232477437326-823787906">
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha2" />
<ds:DigestValue>XXXXXXXXXXXXXXXXXXXXX</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</ds:SignatureValue>
<ds:KeyInfo>
<wsse:SecurityTokenReference xmlns:wsse="http://www.w3.org/2000/09/xmldsig#" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsse:Id="XWSSGID-1232477437311698965010">
<wsse:Reference URI="#XWSSGID-12324774331131695995061" />
<ds:X509Data>
<ds:X509IssuerName>XXXXXXXXXXXXXXXXXXXXXXXXX</ds:X509IssuerName>
<ds:X509SerialNumber>XXXXXXXXXXXXXXXXXXX</ds:X509SerialNumber>
</ds:X509Data>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
<wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="XWSSGID-1232477437326-823787906">
<wsu:Created>2009-01-20T18:50:37.233Z</wsu:Created>
<wsu:Expires>2009-01-20T18:50:42.233Z</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body xmlns:SOAP-ENV="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="XWSSGID-1232477437326-1352495766">
BODY OF MESSAGE GOES HERE
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Got it working here is the final solution
someServiceRef.widjetClient client = null;
try
{
X509Certificate2 signingCert = GetSigningCert();
var bindings = new BasicHttpsBinding();
bindings.Security.Mode = BasicHttpsSecurityMode.TransportWithMessageCredential;
bindings.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
bindings.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Basic256Sha256
var elements = bindings.CreateBindingElements();
elements.Find<SecurityBindingElement>().EnableUnsecuredResponse = true;
var customBindings = new CustomBinding(elements);
client = new someServiceRef.widjetClient(
customBindings,
new EndpointAddress(#"<URL OF SERVICE>"));
client.ClientCredentials.ClientCertificate.Certificate = signingCert;
client.ClientCredentials.ServiceCertificate.DefaultCertificate = signingCert;
client.Open();
var request = BuildRequest();
var response = client.SayHello(request);
Console.WriteLine(response);
}
finally
{
if (client != null)
{
if (client.State == System.ServiceModel.CommunicationState.Faulted)
client.Abort();
else
client.Close();
}
}
i'm trying to sign a xml with SecurityTokenReference for send it to ibm datapower service, but when i send it returns empty cert or error, when i send from SOAPUI DataPower receives ok
I've tried a lot of time with diferent types like: BinarySecurityToken, SecurityTokenReference... but i always get the same error, please help me.
Correct xml:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ser="http://www.example.org/ServiciosAdministrativosCodensa"
xmlns:met="http://www.colpatria.com/services/metadata">
<soapenv:Header>
<wsse:Security xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<ds:Signature Id="SIG-CFB8CEFD4DE1135138158023563139463"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces PrefixList="met ser soapenv"
xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<ds:Reference URI="#id-CFB8CEFD4DE1135138158023563139462">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces PrefixList="met ser"
xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>d4ThIYDCXlPoN6kGvXq+Ntf/XKQ=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>0Ph8zgWSDbWaEkczeu3RbpYmivkWSvzjjqqoUW91JnTR0NuyZhWisLTddbJvvY3xQzmjHuIVL1wW IXjIatJwMgAERjK48EjPXrr+MuMWzo2vAPmA04p2TWiF7vzFCI7pWgWzLk2D2oEx/bn3Xr4wQ2dm l00uT5Cj3B79UIRdTc76s60GBW/7ZOuFySbDywTxjXz1bNArKbS81EZXZH+jw0jk2Esf0wAHSF9u 2VCUeQvPAISKAMsx116bPT3+ReDX4b8XDTvfM1I7pnMZ9broV2adBG3nMW6FTucDEl2oJpfb7y0N CAE38EJjfdmfF/tRUHdmVGzHu8evWgqL9OgkXg==</ds:SignatureValue>
<ds:KeyInfo Id="KI-CFB8CEFD4DE1135138158023563139460">
<wsse:SecurityTokenReference wsu:Id="STR-CFB8CEFD4DE1135138158023563139461">
<wsse:KeyIdentifier 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#X509SubjectKeyIdentifier">0+fjoRhUswYnp4F6biToxgrgnAg=</wsse:KeyIdentifier>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
</wsse:Security>
</soapenv:Header>
<soapenv:Body wsu:Id="id-CFB8CEFD4DE1135138158023563139462"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<ser:activacionTarjetasRequest>
<met:requestHeader>
<met:esbHeader>
<met:transactionId>350278742945543</met:transactionId>
<met:serviceCode>RBMCARD1</met:serviceCode>
<met:operationCode>Update</met:operationCode>
<met:requestUser>PARRAJOH</met:requestUser>
<met:requestSystem>GBM</met:requestSystem>
<met:channel>GBM</met:channel>
<met:host>10.236.224.50</met:host>
<met:executionMode>U</met:executionMode>
<met:operationCountry>057</met:operationCountry>
<met:operationBank>Colpatria</met:operationBank>
<met:transactionDate>2020-01-28</met:transactionDate>
<met:transactionTime>13:20:31</met:transactionTime>
<met:officeCode>9</met:officeCode>
<met:numberPages>01</met:numberPages>
<met:totalPages>01</met:totalPages>
<met:institutionCode>019</met:institutionCode>
<met:usernameToken>
<met:userName>testColDensa</met:userName>
<met:password>w5jgTS26eU</met:password>
</met:usernameToken>
</met:esbHeader>
</met:requestHeader>
<ser:parteFija>
<ser:codAplicacion>25</ser:codAplicacion>
<ser:codTerminal>235-55126-6</ser:codTerminal>
<ser:codEstablecimiento>019</ser:codEstablecimiento>
<ser:fecTransaccion>20190904</ser:fecTransaccion>
<ser:horTransaccion>105523</ser:horTransaccion>
<ser:dispositivo>INTERNET</ser:dispositivo>
<ser:nroAuditoria>123605</ser:nroAuditoria>
<ser:consecutivo>1069735</ser:consecutivo>
<ser:tipTransaccion>NORMAL</ser:tipTransaccion>
<ser:trackII>
<ser:nroCuentaPrimaria>0316552636556352</ser:nroCuentaPrimaria>
<ser:fecVencimiento>0905</ser:fecVencimiento>
<ser:codServicio>562</ser:codServicio>
<ser:campoVerificacionPIN>01234</ser:campoVerificacionPIN>
<ser:cardVerificationCode>2</ser:cardVerificationCode>
</ser:trackII>
</ser:parteFija>
</ser:activacionTarjetasRequest>
</soapenv:Body>
</soapenv:Envelope>
my xml:
<soapenv:Envelope xmlns:ser="http://www.example.org/ServiciosAdministrativosCodensa"
xmlns:met="http://www.colpatria.com/services/metadata"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
<wsse:Security xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509Subjectwsse:KeyIdentifier">
<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#">
<ec:InclusiveNamespaces PrefixList="met ser soapenv"
xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" />
</ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<ds:Reference URI="#id-C758EA542CABFF8A3C158014740919829">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces PrefixList="met ser"
xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" />
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<ds:DigestValue>hALHAC9T8wWZ6+5b9JFAWFwqdKc=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>JHFeMOqW9hqGEgS2gtTlJiRqQfxsd5z88mC0qzOZKtw8/aEdDWBEZU7jwEwUYwym4kgbK8kXrTCfwdT8TFpYy6NEo8Yi3wlQtC3R4buCcVreeSeWRBe9dpDw6loLPR0VsU3qFeO+3NUFMsOG49jzG37DqQVSn/6tz7Ojh7t3zTQY9wWRJdrK2iAbf04+qmNK+ATKWpOEm/waJv4GNT0pQCELQQtJqQj2t6XhPR9LwYJMOcFvB3wpJ0cKjaJ8pUCLYT2WUofNZBrelMUVgQrYrWAJ/q1GYYqfFv1vcdjmja77Q11zH6I55sZPBDJ2vLpDJlmf8YBHcII2zUS5Qs61Tw==</ds:SignatureValue>
<ds:KeyInfo Id="KI-C758EA542CABFF8A3C158014740919527">
<wsse:SecurityTokenReference wsu:Id="STR-C758EA542CABFF8A3C158014740919528"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:KeyIdentifier 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#X509SubjectKeyIdentifier">0+fjoRhUswYnp4F6biToxgrgnAg=</wsse:KeyIdentifier>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
</ds:Signature>
</wsse:Security>
</soapenv:Header>
<soapenv:Body wsu:Id="id-C758EA542CABFF8A3C158014740919829"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<ser:activacionTarjetasRequest>
<met:requestHeader>
<met:esbHeader>
<met:transactionId>100360</met:transactionId>
<met:serviceCode>CRTPINES1</met:serviceCode>
<met:operationCode>Update</met:operationCode>
<met:requestUser>PARRAJOH</met:requestUser>
<met:requestSystem>GBM</met:requestSystem>
<met:channel>GBM</met:channel>
<met:host>10.236.125.242</met:host>
<met:executionMode>U</met:executionMode>
<met:operationCountry>057</met:operationCountry>
<met:operationBank>Colpatria</met:operationBank>
<met:transactionDate>2020-01-30</met:transactionDate>
<met:transactionTime>11:54:58</met:transactionTime>
<met:officeCode>9</met:officeCode>
<met:numberPages>01</met:numberPages>
<met:totalPages>01</met:totalPages>
<met:institutionCode>19</met:institutionCode>
<met:usernameToken />
</met:esbHeader>
</met:requestHeader>
<ser:parteFija>
<ser:codAplicacion>QE</ser:codAplicacion>
<ser:codTerminal>235-55126-D</ser:codTerminal>
<ser:codEstablecimiento>02167306040</ser:codEstablecimiento>
<ser:fecTransaccion>20200130</ser:fecTransaccion>
<ser:horTransaccion>115456</ser:horTransaccion>
<ser:dispositivo>INTERNET</ser:dispositivo>
<ser:nroAuditoria>013422</ser:nroAuditoria>
<ser:consecutivo>000000013422</ser:consecutivo>
<ser:tipTransaccion>NORMAL</ser:tipTransaccion>
<ser:trackII>
<ser:nroCuentaPrimaria>5907120600037112</ser:nroCuentaPrimaria>
<ser:fecVencimiento>1020</ser:fecVencimiento>
<ser:codServicio>562</ser:codServicio>
<ser:campoVerificacionPIN>00000</ser:campoVerificacionPIN>
<ser:cardVerificationCode>0</ser:cardVerificationCode>
</ser:trackII>
</ser:parteFija>
</ser:activacionTarjetasRequest>
</soapenv:Body>
and my code:
public static string SignXml(XmlDocument xmlDoc)
{
xmlDoc.PreserveWhitespace = false;
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
X509Certificate2 cert = GetCertificateBySubject("WSRBM_CFacil_Firma_IIS_DP_dev");
// Create a SignedXml object.
CustomSignedXml signedXml = new CustomSignedXml(xmlDoc);
RSACryptoServiceProvider rsaKey2 = (RSACryptoServiceProvider)cert.PrivateKey;
signedXml.SigningKey = rsaKey2;
// Specify a canonicalization method.
signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
// Set the InclusiveNamespacesPrefixList property.
XmlDsigExcC14NTransform canMethod = (XmlDsigExcC14NTransform)signedXml.SignedInfo.CanonicalizationMethodObject;
canMethod.InclusiveNamespacesPrefixList = "met ser soapenv";
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "#id-C758EA542CABFF8A3C158014740919829";
reference.Type = "";
string referenceDigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1";
reference.DigestMethod = referenceDigestMethod;
XmlDsigExcC14NTransform c14n = new XmlDsigExcC14NTransform();
c14n.InclusiveNamespacesPrefixList = "met ser";
reference.AddTransform(c14n);
signedXml.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
KeyInfoX509Data kdata = new KeyInfoX509Data(cert);
X509ExtensionCollection extensions = cert.Extensions;
SecurityTokenReference skr = new SecurityTokenReference();
skr.Id = "STR-C758EA542CABFF8A3C158014740919528";
foreach (X509Extension extension in extensions)
if (extension.Oid.Value == "2.5.29.14")
{ // OID for SKI extension
X509SubjectKeyIdentifierExtension skiT = extension as X509SubjectKeyIdentifierExtension;
if (skiT != null)
{
kdata.AddSubjectKeyId(skiT.SubjectKeyIdentifier);
skr.KeyIdentifier = new KeyIdentifier(Convert.ToBase64String((byte[])kdata.SubjectKeyIds[0]));
break;
}
}
skr.ValueType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier";
keyInfo.Id = "KI-C758EA542CABFF8A3C158014740919527";
keyInfo.AddClause(skr);
signedXml.KeyInfo = keyInfo;
// Compute the signature.
signedXml.ComputeSignature("ds");
XmlElement xmlDigitalSignature = signedXml.GetXml("ds");
XmlElement root = (XmlElement)xmlDoc.DocumentElement;
root = setPrefix(root, "soapenv:Security", "wsse");
root = setAttr(root, "wsse:Security", "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
root = setAttr(root, "wsse:Security", "xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509Subjectwsse:KeyIdentifier");
//xmlDigitalSignature = setAttr(xmlDigitalSignature, "ds:Signature", "id", "SIG-C758EA542CABFF8A3C158014740919830");
//var export = cert.Export(X509ContentType.Cert, ConfigurationManager.AppSettings["claveP12yCer"]);
//var base64 = Convert.ToBase64String(export);
root.GetElementsByTagName("wsse:Security")[0].AppendChild(xmlDigitalSignature);
return root.OuterXml;
}
thanks.
I have been assigned a task where I (the iDP) need to connect to a service provider.
So far I have the code:
public ActionResult SSO(string SAMLRequest)
{
var model = new ApiSsoModel();
try
{
if (SAMLRequest == null)
throw new ArgumentNullException("The parameter \"SAMLRequest\" is null.");
byte[] decoded2 = Convert.FromBase64String(SAMLRequest);
string decoded3 = string.Empty;
using (MemoryStream stream2 = new MemoryStream(decoded2))
{
using (MemoryStream stream3 = new MemoryStream())
{
using (StreamReader reader3 = new StreamReader(stream3))
{
stream2.Position = 0L;
new DeflateStream(stream2, CompressionMode.Decompress).CopyTo(stream3);
stream3.Position = 0L;
decoded3 = reader3.ReadToEnd();
reader3.Close();
}
stream3.Close();
}
stream2.Close();
}
string assertion = System.IO.File.ReadAllText(Server.MapPath("~/assertion.xml"));
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
XmlDocument assertionDoc = new XmlDocument();
assertionDoc.LoadXml(assertion);
XmlDocument response = new XmlDocument();
response.LoadXml(decoded3);
SignedXml signedXml = new SignedXml(assertionDoc);
Reference reference = new Reference();
signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url;
reference.Uri = "#_79723ebe12aed3704c4d8de6ea16cf90c0d7451da0";
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigExcC14NTransform());
reference.DigestMethod = SignedXml.XmlDsigSHA1Url;
reference.DigestValue = Encoding.ASCII.GetBytes("3jdMJaumbeC3UJ16d8VQJWjKQKU=");
signedXml.AddReference(reference);
signedXml.SigningKey = rsaKey;
HMACSHA256 key = new HMACSHA256();
signedXml.ComputeSignature(key);
XmlElement xmlDigitalSignature = signedXml.GetXml();
assertionDoc.GetElementsByTagName("ds:SignatureValue")[0].InnerText = xmlDigitalSignature.InnerText;
model.Base64EncodedAssertion = Convert.ToBase64String(Encoding.ASCII.GetBytes(assertionDoc.InnerXml));
model.Message += "Success";
}
catch (Exception ex)
{
model.Message = ex.Message;
}
return View(model);
}
I am loading up an assertion file which was provided in an SSO 2.0 documentation file
<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="9f84acebb80533147969eac6a0aead9603c807b5b" Version="2.0" IssueInstant="2015-07-08T09:44:20Z" Destination="https://testdata.redpoints.co.uk/saml/consume" InResponseTo="_e4098d80-0783-0133-f409-7cd1c3f7b75b">
<saml:Issuer>https://openidp.feide.no</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/2000/09/xmldsig#rsa-sha1" />
<ds:Reference URI="#_b9f84acebb80533147969eac6a0aead9603c807b5b">
<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/2000/09/xmldsig#sha1" />
<ds:DigestValue>3jdMJaumbeC3UJ16d8VQJWjKQKU=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>dewQ7U/QjQtaeUHHk/wgzyCLXi0B6mnmMNCUJgj+taxa/c+HsrKVx97iMbMaoFWRd9Ps9SjNr5P40yC2I5j3Dx9pheBAgKX6RRAl0C7CJM36XZAqWwA1CBlDCqx1H3vTeSeotuOovzKVhnpQj9AL38GmFYqHnNS1e5pCfugI72o=</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate>MIICizCCAfQCCQCY8tKaMc0BMjANBgkqhkiG9w0BAQUFADCBiTELMAkGA1UEBhMCTk8xEjAQBgNVBAgTCVRyb25kaGVpbTEQMA4GA1UEChMHVU5JTkVUVDEOMAwGA1UECxMFRmVpZGUxGTAXBgNVBAMTEG9wZW5pZHAuZmVpZGUubm8xKTAnBgkqhkiG9w0BCQEWGmFuZHJlYXMuc29sYmVyZ0B1bmluZXR0Lm5vMB4XDTA4MDUwODA5MjI0OFoXDTM1MDkyMzA5MjI0OFowgYkxCzAJBgNVBAYTAk5PMRIwEAYDVQQIEwlUcm9uZGhlaW0xEDAOBgNVBAoTB1VOSU5FVFQxDjAMBgNVBAsTBUZlaWRlMRkwFwYDVQQDExBvcGVuaWRwLmZlaWRlLm5vMSkwJwYJKoZIhvcNAQkBFhphbmRyZWFzLnNvbGJlcmdAdW5pbmV0dC5ubzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt8jLoqI1VTlxAZ2axiDIThWcAOXdu8KkVUWaN/SooO9O0QQ7KRUjSGKN9JK65AFRDXQkWPAu4HlnO4noYlFSLnYyDxI66LCr71x4lgFJjqLeAvB/GqBqFfIZ3YK/NrhnUqFwZu63nLrZjcUZxNaPjOOSRSDaXpv1kb5k3jOiSGECAwEAATANBgkqhkiG9w0BAQUFAAOBgQBQYj4cAafWaYfjBU2zi1ElwStIaJ5nyp/s/8B8SAPK2T79McMyccP3wSW13LHkmM1jwKe3ACFXBvqGQN0IbcH49hu0FKhYFM/GPDJcIHFBsiyMBXChpye9vBaTNEBCtU3KjjyG0hRT2mAQ9h+bkPmOvlEo/aH0xR68Z9hw4PF13w==</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</ds:Signature>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
<saml:Assertion xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ID="_79723ebe12aed3704c4d8de6ea16cf90c0d7451da0" Version="2.0" IssueInstant="2015-07-08T09:44:20Z">
<saml:Issuer>https://openidp.feide.no</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/2000/09/xmldsig#rsa-sha1" />
<ds:Reference URI="#_79723ebe12aed3704c4d8de6ea16cf90c0d7451da0">
<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/2000/09/xmldsig#sha1" />
<ds:DigestValue>sDFB4zP6PHBacygh64DRtaeowZ8=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>GY1M5iO5yht1JLOAOmFBUdZPtxKZeek5jG77w7Ct6A+H1qbUAbX7u8PmniGdOXkllxPWqB+L4Gtd39WbCEoWiQ9QvY/pVz2xe6xzI9gVsnJBP0alalyCZglnxNpQ2x+692OcpVXnbau4LJoFv2+0zktXPhQEI3CfAyixOpASu1w=</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate>MIICizCCAfQCCQCY8tKaMc0BMjANBgkqhkiG9w0BAQUFADCBiTELMAkGA1UEBhMCTk8xEjAQBgNVBAgTCVRyb25kaGVpbTEQMA4GA1UEChMHVU5JTkVUVDEOMAwGA1UECxMFRmVpZGUxGTAXBgNVBAMTEG9wZW5pZHAuZmVpZGUubm8xKTAnBgkqhkiG9w0BCQEWGmFuZHJlYXMuc29sYmVyZ0B1bmluZXR0Lm5vMB4XDTA4MDUwODA5MjI0OFoXDTM1MDkyMzA5MjI0OFowgYkxCzAJBgNVBAYTAk5PMRIwEAYDVQQIEwlUcm9uZGhlaW0xEDAOBgNVBAoTB1VOSU5FVFQxDjAMBgNVBAsTBUZlaWRlMRkwFwYDVQQDExBvcGVuaWRwLmZlaWRlLm5vMSkwJwYJKoZIhvcNAQkBFhphbmRyZWFzLnNvbGJlcmdAdW5pbmV0dC5ubzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt8jLoqI1VTlxAZ2axiDIThWcAOXdu8KkVUWaN/SooO9O0QQ7KRUjSGKN9JK65AFRDXQkWPAu4HlnO4noYlFSLnYyDxI66LCr71x4lgFJjqLeAvB/GqBqFfIZ3YK/NrhnUqFwZu63nLrZjcUZxNaPjOOSRSDaXpv1kb5k3jOiSGECAwEAATANBgkqhkiG9w0BAQUFAAOBgQBQYj4cAafWaYfjBU2zi1ElwStIaJ5nyp/s/8B8SAPK2T79McMyccP3wSW13LHkmM1jwKe3ACFXBvqGQN0IbcH49hu0FKhYFM/GPDJcIHFBsiyMBXChpye9vBaTNEBCtU3KjjyG0hRT2mAQ9h+bkPmOvlEo/aH0xR68Z9hw4PF13w==</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</ds:Signature>
<saml:Subject>
<saml:NameID SPNameQualifier="https://testdata.redpoints.co.uk/saml/metadata" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">_36355e0a362adec0f5753911aff3b14f9b21d9c2b8</saml:NameID>
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData NotOnOrAfter="2017-11-08T09:49:20Z" Recipient="https://testdata.redpoints.co.uk/saml/consume" InResponseTo="_e4098d80-0783-0133-f409-7cd1c3f7b75b" />
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2015-07-08T09:43:50Z" NotOnOrAfter="2017-11-08T09:49:20Z">
<saml:AudienceRestriction>
<saml:Audience>https://testdata.redpoints.co.uk/saml/metadata</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2015-07-08T09:15:58Z" SessionNotOnOrAfter="2017-11-08T17:44:20Z" SessionIndex="_066bce0e07565d6a61ae7e94fe95d8bcdd79a3cfd0">
<saml:AuthnContext>
<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
<saml:AttributeStatement>
<saml:Attribute Name="uid" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
<saml:AttributeValue xsi:type="xs:string">102112</saml:AttributeValue>
</saml:Attribute>
</saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>
I have tried many different methods to make this work, downloading multiple .net libraries which are meant to help with setting up SSO for the iDP but not had no luck.
My reply might not help you but at least it gives you few ideas.
there are 2 flows in SAML:
Sp-Initiated [Service Provider Initiated]: Service provider starts the flow by sending SSO SAML request to the Idp. Idp server process the request and make sure that user is authenticated and authorized to use this service then Idp sends SSO SAML response to Service provider (SP) contains assertions (data about authenticated user).
Idp-Initiated [Identity Provider Initiated]: Idp authenticate and authorize the user and send SSO SAML Request to Service Provider (Only the second part of the Sp-Initiated).
As you are waiting for SAML request. That means your flow is SP-Initiated.
First you need to generate your meta data and send it to redpoints. This meta data should at least includes your entityId and SSO end point and X.509 cert for sign/encrypt.
You can use onlogin website to generate your metadata
If you already did that. I would recommend you use https://www.componentspace.com/ library. It is fast, efficient and well-maintained. Unfortunately, It is paid but there is a trial period so you can test it.
Have a look on the library documentation on this link
If you use this library, all what you need to do is to add saml.config file as following
<?xml version="1.0"?>
<SAMLConfiguration xmlns="urn:componentspace:SAML:2.0:configuration">
<IdentityProvider Name="YourEntityId"
Description="Description"
LocalCertificateFile="Your certificate private key *.pfx"
LocalCertificatePassword="Your certificate password"/>
<PartnerServiceProviders>
<PartnerServiceProvider Name="https://testdata.redpoints.co.uk/saml/metadata"
Description="Red Point Service Provider"
<!-- those options should be based on redpoint metadata WantAuthnRequestSigned="true"
SignSAMLResponse="false"
SignAssertion="true"
EncryptAssertion="false"-->
AssertionConsumerServiceUrl="https://testdata.redpoints.co.uk/saml/consume"
PartnerCertificateFile="Path to redpoint certificate file .cer"/>
</PartnerServiceProviders>
</SAMLConfiguration>
and add to your action method the following:
SAMLConfigurationFile.Load();
string partnerSP = null;
SSOOptions options = null;
SAMLIdentityProvider.ReceiveSSO(Request, out partnerSP, out options);
string userName = "robert#test.com";
IDictionary<string, string> attributes = new Dictionary<string, string>();
attributes.Add("NameID", "robert#test.com"); // as an example for possible attribute
SAMLIdentityProvider.SendSSO(Response, userName, attributes);
I would recommend you also install browser extension to detect SAML requests/response. This is will help you to see the output that you are sending.
I hope my reply gives you a little help.
There are a number of SAML stacks around - SAML : SAML connectivity / toolkit .
I would definitely suggest that you don't roll your own. You'll fix this only to come across the next problem.
The problem with most of the stacks is that they are client side. You want server side.
Agree with componentspace suggestion - it can do both sides.
Or this one - currently in beta.
Or have a look at the OpenSAML source - it's Java but the principles are the same.
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>