Пример #1
0
        public static Transform fromURI(string uri)
        {
            Transform t = null;

            switch (uri)
            {
            case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315":
                t = new XmlDsigC14NTransform();
                break;

            case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments":
                t = new XmlDsigC14NWithCommentsTransform();
                break;

            case "http://www.w3.org/2000/09/xmldsig#enveloped-signature":
                t = new XmlDsigEnvelopedSignatureTransform();
                break;

            case "http://www.w3.org/TR/1999/REC-xpath-19991116":
                t = new XmlDsigXPathTransform();
                break;

            case "http://www.w3.org/TR/1999/REC-xslt-19991116":
                t = new XmlDsigXsltTransform();
                break;

            case "http://www.w3.org/2001/10/xml-exc-c14n#":
                t = new XmlDsigExcC14NTransform();
                break;
            }
            return(t);
        }
        public void Constructor()
        {
            XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform();

            Assert.Null(xmlDsigC14NWithCommentsTransform.Context);
            Assert.Equal("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments", xmlDsigC14NWithCommentsTransform.Algorithm);
            Assert.Equal(new[] { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }, xmlDsigC14NWithCommentsTransform.InputTypes);
            Assert.Equal(new[] { typeof(Stream) }, xmlDsigC14NWithCommentsTransform.OutputTypes);
        }
Пример #3
0
        public void FullChain()
        {
            TransformChain chain = new TransformChain();

            XmlDsigBase64Transform base64 = new XmlDsigBase64Transform();

            chain.Add(base64);
            Assert.Equal(base64, chain[0]);
            Assert.Equal(1, chain.Count);

            XmlDsigC14NTransform c14n = new XmlDsigC14NTransform();

            chain.Add(c14n);
            Assert.Equal(c14n, chain[1]);
            Assert.Equal(2, chain.Count);

            XmlDsigC14NWithCommentsTransform c14nc = new XmlDsigC14NWithCommentsTransform();

            chain.Add(c14nc);
            Assert.Equal(c14nc, chain[2]);
            Assert.Equal(3, chain.Count);

            XmlDsigEnvelopedSignatureTransform esign = new XmlDsigEnvelopedSignatureTransform();

            chain.Add(esign);
            Assert.Equal(esign, chain[3]);
            Assert.Equal(4, chain.Count);

            XmlDsigXPathTransform xpath = new XmlDsigXPathTransform();

            chain.Add(xpath);
            Assert.Equal(xpath, chain[4]);
            Assert.Equal(5, chain.Count);

            XmlDsigXsltTransform xslt = new XmlDsigXsltTransform();

            chain.Add(xslt);
            Assert.Equal(xslt, chain[5]);
            Assert.Equal(6, chain.Count);
        }
Пример #4
0
        public static string GetObject2(XmlDocument doc, string id)
        {
            var signedXml = new SignedXmlObject(doc)
            {
                KeyInfo = new KeyInfo(), SigningKey = (RSA) new RSACryptoServiceProvider()
            };

            var transform1 = new XmlDsigEnvelopedSignatureTransform();
            var transform2 = new XmlDsigC14NWithCommentsTransform();


            var reference = new Reference {
                Uri = id
            };

            reference.AddTransform(transform1);
            reference.AddTransform(transform2);
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();
            //signedXml.

            AsymmetricAlgorithm algorithm = new ECDsaCng();

            signedXml.CheckSignature(algorithm);

            var result = new StreamReader((MemoryStream)transform2.GetOutput()).ReadToEnd();

            if (!Verify(result, reference.DigestValue))
            {
                throw new Exception("Wrong canonicalization object");
            }

            //using (var file = File.CreateText(id.Replace("#", "canonical2-") + ".txt"))
            //{
            //  file.WriteLine(result);
            //}

            return(result);
        }
        private string ExecuteXmlDSigC14NTransform(string inputXml, Encoding encoding = null, XmlResolver resolver = null)
        {
            XmlDocument doc = new XmlDocument();

            doc.XmlResolver        = resolver;
            doc.PreserveWhitespace = true;
            doc.LoadXml(inputXml);

            Encoding actualEncoding = encoding ?? Encoding.UTF8;

            byte[] data = actualEncoding.GetBytes(inputXml);
            using (Stream stream = new MemoryStream(data))
                using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings {
                    ValidationType = ValidationType.None, DtdProcessing = DtdProcessing.Parse, XmlResolver = resolver
                }))
                {
                    doc.Load(reader);
                    XmlDsigC14NWithCommentsTransform transform = new XmlDsigC14NWithCommentsTransform();
                    transform.LoadInput(doc);
                    return(TestHelpers.StreamToString((Stream)transform.GetOutput(), actualEncoding));
                }
        }
        public void GetOutput_UnsupportedType(Type type)
        {
            XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform();

            AssertExtensions.Throws <ArgumentException>("type", () => xmlDsigC14NWithCommentsTransform.GetOutput(type));
        }
        public void LoadInput_UnsupportedType(object input)
        {
            XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform();

            AssertExtensions.Throws <ArgumentException>("obj", () => xmlDsigC14NWithCommentsTransform.LoadInput(input));
        }
Пример #8
0
        /// <summary>
        /// Takes a document
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string AddIRMark(ref XmlDocument originalDoc, string ManifestNameSpace)
        {
            try
            {
                if ((originalDoc == null) || (originalDoc.ChildNodes.Count == 0))
                {
                    return("");
                }

                // Load XML Return
                originalDoc.PreserveWhitespace = false;
                //              originalDoc.WriteTo(new XmlTextWriter("c:\\OriginalDoc.xml", Encoding.ASCII));

                // Step 1. Clone the original document and create a workspace object
                XmlDocument canonDoc = new XmlDocument();
                canonDoc.LoadXml(originalDoc.OuterXml);


                // We also pick up the name table from the original document
                XmlNamespaceManager nsMgr = new XmlNamespaceManager(canonDoc.NameTable);

                // Define namespaces within the document:
                nsMgr.AddNamespace("ir", ManifestNameSpace);                       // Define a namespace for the IRheader
                nsMgr.AddNamespace("gt", "http://www.govtalk.gov.uk/CM/envelope"); // Define a namespace for the GovTalk element


                XmlNode bodyNode = null;
                try
                {
                    // Step 2. Find the Body node and add the GovTalk namespace to it.
                    // Originally was using select single node but this has been replced
                    // with GetElementByTagName as SelectSingleNode has cannot be used
                    // through the COM interface.

                    //bodyNode = canonDoc.SelectSingleNode("//gt:Body", nsMgr);

                    XmlNodeList BodyNodeList = canonDoc.GetElementsByTagName("Body", "http://www.govtalk.gov.uk/CM/envelope");
                    bodyNode = BodyNodeList[0];

                    bodyNode.Attributes.Append(canonDoc.CreateAttribute("xmlns"));
                    bodyNode.Attributes["xmlns"].Value = "http://www.govtalk.gov.uk/CM/envelope";
                }
                catch (Exception ex)
                {
                    throw ex;
                }



                // Step 2. Find the IRmark and remove it
                // Originally was using select single node but this has been replced
                // with GetElementByTagName as SelectSingleNode has cannot be used
                // through the COM interface.

                //              XmlNode IRheader = canonDoc.SelectSingleNode("//ir:IRheader", nsMgr);
                //              XmlNode irMarkNode = IRheader.SelectSingleNode("//ir:IRmark", nsMgr);

                //if (irMarkNode != null)
                //    IRheader.RemoveChild(irMarkNode);


                XmlNodeList IRHeaderNodeList;
//              XmlNodeList irMarkNodeList;
                XmlNode IRheader;
                XmlNode irMarkNode;

                IRHeaderNodeList = canonDoc.GetElementsByTagName("IRheader", ManifestNameSpace);
                IRheader         = IRHeaderNodeList[0];

                foreach (XmlNode SearchNode in IRheader.ChildNodes)
                {
                    if (SearchNode.Name == "IRmark")
                    {
                        SearchNode.ParentNode.RemoveChild(SearchNode);
                    }
//                      SearchNode.RemoveAll();
                }

                //Step 4. Generate IRmark
                canonDoc.PreserveWhitespace = true;


                // 4a. Extract <Body /> element into an XmlDocument
                XmlDocument workSpace = new XmlDocument();
                workSpace.LoadXml(bodyNode.OuterXml);



                // 4b. Canonicalise Document
                XmlDsigC14NWithCommentsTransform transform = new XmlDsigC14NWithCommentsTransform();
                transform.LoadInput(workSpace);


                // 4c. Create SHA1 digest
                Stream s    = (Stream)transform.GetOutput(typeof(Stream));
                SHA1   sha1 = SHA1.Create();


                // 4d. Compute byte-array hash
                byte[] hash = sha1.ComputeHash(s);


                // Step 5. Replace the IRmark in the original document with the computed hash
                // Originally was using select single node but this has been replced
                // with GetElementByTagName as SelectSingleNode has cannot be used
                // through the COM interface.

                //              irMarkNode = originalDoc.SelectSingleNode("//ir:IRmark", nsMgr);
                XmlNodeList irMarkNodeList2;
                irMarkNodeList2 = originalDoc.GetElementsByTagName("IRmark", ManifestNameSpace);
                irMarkNode      = irMarkNodeList2[0];
                if (irMarkNode == null)
                {
                    // Add the IRMark at the specified location
                    //                  XmlNode parentNode = originalDoc.SelectSingleNode("//ir:IRheader");
                    //                  XmlNode precedingNode = originalDoc.SelectSingleNode("//ir:Sender");
                    XmlNodeList parentNodeList;
                    XmlNodeList precedingNodeList;

                    parentNodeList    = originalDoc.GetElementsByTagName("IRheader", ManifestNameSpace);
                    precedingNodeList = originalDoc.GetElementsByTagName("Sender", ManifestNameSpace);
                    XmlNode parentNode    = parentNodeList[0];
                    XmlNode precedingNode = precedingNodeList[0];

                    irMarkNode = originalDoc.CreateElement("IRmark");
                    parentNode.InsertBefore(irMarkNode, precedingNode);
                }


                // 5a. Create the "Type" attribute if it does not exist
                bool found = false;
                foreach (XmlAttribute attr in irMarkNode.Attributes)
                {
                    if (attr.Name == "Type")
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    irMarkNode.Attributes.Prepend(originalDoc.CreateAttribute("Type"));
                }


                // 5b. Assign the "Type" attribute the value of "generic"
                irMarkNode.Attributes["Type"].Value = "generic";


                // 5c. Convert the IRmark byte-array to a Base-64 string and set the  node with this value:
                irMarkNode.InnerText = Convert.ToBase64String(hash);


                // 6. Return the IRmark in Base32.
                return(IRMark32.ToBase32String(hash));
            }
            catch // (Exception ex)
            {
                return("Failed the genration of the IR Mark");
            }

            // The following code is unreachable and causes a compiler warning
            // return "Failed the genration of the IR Mark";
        }
Пример #9
0
        public string SignXml(XmlDocument xmlDoc, X509Certificate2 cert, ILogger _logger)
        {
            var Key = (RSACryptoServiceProvider)cert.PrivateKey;

            // Check arguments.
            try
            {
                if (xmlDoc == null)
                {
                    throw new ArgumentException("xmlDoc");
                }
                if (cert == null)
                {
                    throw new ArgumentException("Certificate");
                }
            }
            catch (Exception e)
            {
                _logger.Info(e.Message, "Request");
            }

            var signedXml = new SignedXml(xmlDoc);

            var XMLSignature = signedXml.Signature;

            signedXml.SigningKey = Key;


            var reference = new Reference("#Header");
            var env       = new XmlDsigEnvelopedSignatureTransform();
            var c14n      = new XmlDsigC14NWithCommentsTransform();

            reference.AddTransform(env);
            reference.AddTransform(c14n);
            signedXml.AddReference(reference);
            var reference1 = new Reference("#Body");
            var env1       = new XmlDsigEnvelopedSignatureTransform();
            var c14n1      = new XmlDsigC14NWithCommentsTransform();

            reference1.AddTransform(env1);
            reference1.AddTransform(c14n1);
            signedXml.AddReference(reference1);

            var keyInfo = new KeyInfo();

            keyInfo.AddClause(new KeyInfoX509Data(cert));

            XMLSignature.KeyInfo = keyInfo;
            try
            {
                signedXml.ComputeSignature();
            }
            catch (Exception e)
            {
                _logger.Info(e.Message + "==== Non existing Body or Header atributes!!!", "Request");
            }
            var xmlDigitalSignature = signedXml.GetXml();

            XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);

            ns.AddNamespace("mioa", "http://mioa.gov.mk/interop/mim/v1");

            try
            {
                var sig = xmlDoc.SelectSingleNode("//mioa:Signature", ns);
                sig.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
            }
            catch (Exception e)
            {
                _logger.Info(e.Message + "==== Non existing mioa:Signature tag!!!", "Request");
            }
            return(xmlDoc.InnerXml);
        }
Пример #10
0
        public String BuildSamlAssertion(AttributeHolder attributes)
        {
            XmlDocument xmlDoc = new XmlDocument();

            //required by World Wide Web Consortium (W3C) for digitial signatures
            xmlDoc.PreserveWhitespace = true;

            #region Build the SAML 2.0 Root Element

            XElement root = new XElement(saml2 + "Assertion",
                                         new XAttribute(XNamespace.Xmlns + "saml2", saml2.ToString()),
                                         new XAttribute(XNamespace.Xmlns + "xs", xs.ToString()),
                                         new XAttribute("ID", attributes.Id),
                                         new XAttribute("IssueInstant", attributes.IssueInstant),
                                         new XAttribute("Version", "2.0"));
            XElement issuer = new XElement(saml2 + "Issuer",
                                           new XAttribute("Format", "urn:oasis:names:tc:SAML:2.0:nameid-format:entity"), attributes.ElectronicEntityId);
            root.Add(issuer);
            xmlDoc.Load(root.CreateReader());

            #endregion

            #region Build the Conditions Block

            /*.Net seems to process much quicker than JAVA, and so we set the NotBefore condition back by
             * 10 seconds so that when the request is sent we don't run into problems of not meeting our own
             * conditions on the ISI.  This was a problem found during testing, and this seems to have resolved
             * the issue. */
            TimeSpan ts = new TimeSpan(0, 0, 10);

            XElement conditions = new XElement(saml2 + "Conditions",
                                               new XAttribute("NotBefore", DateTime.Now.Subtract(ts).ToUniversalTime()),
                                               new XAttribute("NotOnOrAfter", DateTime.Now.AddMonths(12).ToUniversalTime()));
            XElement restrictions = new XElement(saml2 + "AudienceRestriction");
            XElement audience     = new XElement(saml2 + "Audience", "urn:mise:all");
            restrictions.Add(new XElement(audience));
            conditions.Add(new XElement(restrictions));

            XmlNode conditionNode = xmlDoc.ReadNode(conditions.CreateReader());
            xmlDoc.DocumentElement.AppendChild(conditionNode);

            #endregion

            #region Build the Attribute Statement Block

            XElement attributeHolder = new XElement(saml2 + "AttributeStatement");
            attributeHolder.Add(this.AssertionBuilder("ElectronicIdentityId", "mise:1.2:user:ElectronicIdentityId", "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified", attributes.ElectronicEntityId));
            attributeHolder.Add(this.AssertionBuilder("FullName", "mise:1.2:user:FullName", "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified", attributes.FullName));
            attributeHolder.Add(this.AssertionBuilder("CitizenshipCode", "mise:1.2:user:CitizenshipCode", "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified", attributes.CitizenCodes));
            attributeHolder.Add(this.AssertionBuilder("Scope", "mise:1.2:user:Scope", "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified", attributes.Scope));
            attributeHolder.Add(this.AssertionBuilder("LawEnforcementIndicator", "mise:1.2:user:LawEnforcementIndicator", "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified", attributes.LEI.ToString()));
            attributeHolder.Add(this.AssertionBuilder("PrivacyProtectedIndicator", "mise:1.2:user:PrivacyProtectedIndicator", "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified", attributes.PPI.ToString()));
            attributeHolder.Add(this.AssertionBuilder("COIIndicator", "mise:1.2:user:COIIndicator", "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified", attributes.COI.ToString()));
            XmlNode attrNode = xmlDoc.ReadNode(attributeHolder.CreateReader());
            xmlDoc.DocumentElement.AppendChild(attrNode);

            #endregion

            //need to sign after all other nodes have been created
            #region Build the Signature Block

            SignedXml signedXml = new SignedXml(xmlDoc);
            signedXml.SigningKey = _privateCert.PrivateKey;

            Reference reference = new Reference();
            reference.Uri = "";

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true);
            env.Algorithm = SignedXml.XmlDsigEnvelopedSignatureTransformUrl;
            reference.AddTransform(env);

            //With respect to the trustfabric the transform c14t with comments are required
            //for the interoperability between c# and java
            XmlDsigC14NWithCommentsTransform c14t = new XmlDsigC14NWithCommentsTransform();
            c14t.Algorithm = SignedXml.XmlDsigC14NWithCommentsTransformUrl;
            reference.AddTransform(c14t);

            KeyInfo         keyInfo     = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(_privateCert);
            keyInfo.AddClause(keyInfoData);

            signedXml.KeyInfo = keyInfo;
            signedXml.AddReference(reference);
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            signedXml.ComputeSignature();

            XmlElement assignedSignature = signedXml.GetXml();
            //insert the cert in the correct document location (not necassary will work if appendchild is used)
            xmlDoc.DocumentElement.InsertBefore(xmlDoc.ImportNode(assignedSignature, true), conditionNode);

            #endregion

            return(xmlDoc.OuterXml);
        }