public static string SignXml(string xml, bool includeKeyInfo = false, bool preserveWhitespace = true)
        {
            var xmlDoc = new XmlDocument { PreserveWhitespace = preserveWhitespace };
            xmlDoc.LoadXml(xml);

            xmlDoc.Sign(TestCert, includeKeyInfo);

            return xmlDoc.OuterXml;
        }        
        public static string SignXml(string xml)
        {
            var xmlDoc = new XmlDocument { PreserveWhitespace = true };
            xmlDoc.LoadXml(xml);

            xmlDoc.Sign(TestCert);

            return xmlDoc.OuterXml;
        }
        public void XmlDocumentExtensions_Sign()
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml("<root><content>Some Content</content></root>");

            xmlDoc.Sign(TestCert);

            var signature = xmlDoc.DocumentElement["Signature", SignedXml.XmlDsigNamespaceUrl];

            var signedXml = new SignedXml(xmlDoc);

            signedXml.LoadXml(signature);

            signedXml.CheckSignature(TestCert, true).Should().BeTrue();
        }
        public ActionResult Index()
        {
            var request = XElement.Load(Request.InputStream);

            var artifact = request
                .Element(Saml2Namespaces.SoapEnvelope + "Body")
                .Element(Saml2Namespaces.Saml2P + "ArtifactResolve")
                .Element(Saml2Namespaces.Saml2P + "Artifact")
                .Value;

            var requestId = request
                .Element(Saml2Namespaces.SoapEnvelope + "Body")
                .Element(Saml2Namespaces.Saml2P + "ArtifactResolve")
                .Attribute("ID").Value;

            var binaryArtifact = Convert.FromBase64String(artifact);

            ISaml2Message message = null;
            if(!Saml2ArtifactBinding.PendingMessages.TryRemove(binaryArtifact, out message))
            {
                throw new InvalidOperationException("Unknown artifact");
            }

            var xml = message.ToXml();

            if(message.SigningCertificate != null)
            {
                var xmlDoc = new XmlDocument()
                {
                    PreserveWhitespace = true
                };

                xmlDoc.LoadXml(xml);
                xmlDoc.Sign(message.SigningCertificate, true);
                xml = xmlDoc.OuterXml;
            }

            var response = string.Format(
                CultureInfo.InvariantCulture,
                ResponseFormatString,
                new Saml2Id().Value,
                requestId,
                DateTime.UtcNow.ToSaml2DateTimeString(),
                xml);

            return Content(response);
        }
        public static string ToXmlString(this MetadataBase metadata, X509Certificate2 signingCertificate)
        {
            var serializer = ExtendedMetadataSerializer.WriterInstance;

            var xmlDoc = new XmlDocument();
            using (var xmlWriter = xmlDoc.CreateNavigator().AppendChild())
            {
                serializer.WriteMetadata(xmlWriter, metadata);
            }

            if (signingCertificate != null)
            {
                xmlDoc.Sign(signingCertificate, true);
            }

            return xmlDoc.OuterXml;
        }
        public void XmlDocumentExtensions_Sign()
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml("<root ID=\"rootElementId\"><content>Some Content</content></root>");

            xmlDoc.Sign(TestCert);

            var signature = xmlDoc.DocumentElement["Signature", SignedXml.XmlDsigNamespaceUrl];

            signature["SignedInfo", SignedXml.XmlDsigNamespaceUrl]
                ["Reference", SignedXml.XmlDsigNamespaceUrl].Attributes["URI"].Value
                .Should().Be("#rootElementId");

            var signedXml = new SignedXml(xmlDoc);
            signedXml.LoadXml(signature);
            signedXml.CheckSignature(TestCert, true).Should().BeTrue();
        }
        public override CommandResult Bind(ISaml2Message message)
        {
            if(message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var xml = message.ToXml();
            if(message.SigningCertificate != null)
            {
                var xmlDoc = new XmlDocument()
                {
                    PreserveWhitespace = true
                };

                xmlDoc.LoadXml(xml);
                xmlDoc.Sign(message.SigningCertificate, true);
                xml = xmlDoc.OuterXml;
            }

            var encodedXml = Convert.ToBase64String(Encoding.UTF8.GetBytes(xml));

            var relayStateHtml = string.IsNullOrEmpty(message.RelayState) ? null
                : string.Format(CultureInfo.InvariantCulture, PostHtmlRelayStateFormatString, message.RelayState);

            var cr = new CommandResult()
            {
                ContentType = "text/html",
                Content = String.Format(
                    CultureInfo.InvariantCulture,
                    PostHtmlFormatString,
                    message.DestinationUrl,
                    relayStateHtml,
                    message.MessageName,
                    encodedXml)
            };

            return cr;
        }
        private void CreateXmlDocument()
        {
            var xml = new XmlDocument();
            xml.AppendChild(xml.CreateXmlDeclaration("1.0", null, null));

            var responseElement = xml.CreateElement("saml2p", "Response", Saml2Namespaces.Saml2PName);

            if (DestinationUrl != null)
            {
                responseElement.SetAttributeNode("Destination", "").Value = DestinationUrl.ToString();
            }

            responseElement.SetAttributeNode("ID", "").Value = id.Value;
            responseElement.SetAttributeNode("Version", "").Value = "2.0";
            responseElement.SetAttributeNode("IssueInstant", "").Value =
                DateTime.UtcNow.ToSaml2DateTimeString();
            if (InResponseTo != null)
            {
                responseElement.SetAttributeNode("InResponseTo", "").Value = InResponseTo.Value;
            }
            xml.AppendChild(responseElement);

            var issuerElement = xml.CreateElement("saml2", "Issuer", Saml2Namespaces.Saml2Name);
            issuerElement.InnerText = issuer.Id;
            responseElement.AppendChild(issuerElement);

            var statusElement = xml.CreateElement("saml2p", "Status", Saml2Namespaces.Saml2PName);
            var statusCodeElement = xml.CreateElement("saml2p", "StatusCode", Saml2Namespaces.Saml2PName);
            statusCodeElement.SetAttributeNode("Value", "").Value = StatusCodeHelper.FromCode(Status);
            statusElement.AppendChild(statusCodeElement);
            responseElement.AppendChild(statusElement);

            foreach (var ci in claimsIdentities)
            {
                responseElement.AppendChild(xml.ReadNode(
                    ci.ToSaml2Assertion(issuer).ToXElement().CreateReader()));
            }

            xmlDocument = xml;

            xml.Sign(issuerCertificate);
        }
        /// <summary>
        /// Serializes the message into wellformed Xml.
        /// </summary>
        /// <returns>string containing the Xml data.</returns>
        public override string ToXml()
        {
            if (SigningCertificate == null)
            {
                return ToXElement().ToString();
            }
            else
            {
                var xml = ToXElement();

                var xmlDocument = new XmlDocument();
                using (var xmlReader = xml.CreateReader())
                {
                    xmlDocument.Load(xmlReader);
                }
                switch (SigningAlgorithm)
                {
                    case AuthenticationRequestSigningAlgorithm.Sha1:
                        xmlDocument.Sign(SigningCertificate);
                        break;
                    case AuthenticationRequestSigningAlgorithm.Sha256:
                        xmlDocument.Sign256(SigningCertificate, false);
                        break;
                }

                return xmlDocument.OuterXml;
            }
        }
        /// <summary>
        /// Serializes the message into wellformed Xml.
        /// </summary>
        /// <returns>string containing the Xml data.</returns>
        public override string ToXml()
        {
            if (SigningCertificate == null)
            {
                return ToXElement().ToString();
            }
            else
            {
                var xml = ToXElement();

                var xmlDocument = new XmlDocument();
                using (var xmlReader = xml.CreateReader())
                {
                    xmlDocument.Load(xmlReader);
                }

                xmlDocument.Sign(SigningCertificate);

                return xmlDocument.OuterXml;
            }
        }
        public void XmlDocumentExtensions_Sign_Nullcheck_Cert()
        {
            XmlDocument xd = new XmlDocument();
            Action a = () => xd.Sign(null);

            a.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("cert");
        }