Ejemplo n.º 1
0
        public static bool IsEqual <T>(T param1, T param2)
            where T : class
        {
            if (param1 == null && param2 == null)
            {
                return(true);
            }

            if (param1 == null || param2 == null)
            {
                return(false);
            }

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            using (MemoryStream stream1 = new MemoryStream(), stream2 = new MemoryStream())
            {
                serializer.Serialize(stream1, param1);
                serializer.Serialize(stream2, param2);

                stream1.Seek(0, SeekOrigin.Begin);
                stream2.Seek(0, SeekOrigin.Begin);
                Stream canonicalizedStream1 = null, canonicalizedStream2 = null;
                try
                {
                    XmlDsigC14NTransform xmlCanonicalizer = new XmlDsigC14NTransform();
                    xmlCanonicalizer.LoadInput(stream1);
                    canonicalizedStream1 = (Stream)xmlCanonicalizer.GetOutput(typeof(Stream));

                    xmlCanonicalizer.LoadInput(stream2);
                    canonicalizedStream2 = (Stream)xmlCanonicalizer.GetOutput(typeof(Stream));

                    canonicalizedStream1.Seek(0, SeekOrigin.Begin);
                    canonicalizedStream2.Seek(0, SeekOrigin.Begin);

                    return(Equals(new StreamReader(canonicalizedStream1).ReadToEnd(), new StreamReader(canonicalizedStream2).ReadToEnd()));
                }
                finally
                {
                    if (canonicalizedStream1 != null)
                    {
                        canonicalizedStream1.Close();
                    }

                    if (canonicalizedStream2 != null)
                    {
                        canonicalizedStream2.Close();
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public static void  Ass()
        {
            string      path = @"C:\Users\Tina\Documents\Visual Studio 2015\Projects\Document\XMLFile2.xml";
            XmlDocument xDoc = new XmlDocument();

            xDoc.PreserveWhitespace = true;
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                xDoc.Load(fs);
            }
            //  XmlElement elem = (XmlElement)xDoc.DocumentElement.FirstChild;
            //XmlNamespaceManager ns = new XmlNamespaceManager(xDoc.NameTable);
            //ns.AddNamespace("env", xDoc.DocumentElement.NamespaceURI);
            //XmlNode Body = xDoc.SelectSingleNode("//env:Child1", ns);
            //ns.AddNamespace("tax", Body.FirstChild.NamespaceURI);

            //   Create an XML document of just the body section
            //XmlDocument xmlBody = new XmlDocument();
            //xmlBody.PreserveWhitespace = true;
            //xmlBody.LoadXml(Body.OuterXml);

            //  Remove any existing IRMark
            //XmlNode nodeIr = xmlBody.SelectSingleNode("//tax:Child2", ns);
            //if (nodeIr != null)
            //{
            //    nodeIr.ParentNode.RemoveChild(nodeIr);
            //}

            //Normalise the document using C14N(Canonicalisation)
            XmlDsigC14NTransform c14n = new XmlDsigC14NTransform();

            c14n.LoadInput(xDoc);

            Stream S = (Stream)c14n.GetOutput();
        }
Ejemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="source_xml"></param>
        /// <returns></returns>
        public MemoryStream Dsig14NTransformToStream(Stream source_xml)
        {
            MemoryStream _result = new MemoryStream();

            XmlDsigC14NTransform _14nTransform = new XmlDsigC14NTransform(true);

            {
                _14nTransform.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl;

                Type[] _validInTypes = _14nTransform.InputTypes;

                for (int i = 0; i < _validInTypes.Length; i++)
                {
                    if (_validInTypes[i] == typeof(System.IO.Stream))
                    {
                        _14nTransform.LoadInput(source_xml);
                        break;
                    }
                }

                Type[] _validOutTypes = _14nTransform.OutputTypes;

                for (int i = 0; i < _validOutTypes.Length; i++)
                {
                    if (_validOutTypes[i] == typeof(System.IO.Stream))
                    {
                        Type streamType = typeof(System.IO.Stream);
                        _result = (MemoryStream)_14nTransform.GetOutput(streamType);
                        break;
                    }
                }
            }

            return(_result);
        }
Ejemplo n.º 4
0
        private string Canonicalize(XmlDocument doc, IList <XmlNode> nsl = null)
        {
            var transform = new XmlDsigC14NTransform {
                Algorithm = CanonicalizationAlgorithm
            };
            var sb = new StringBuilder();

            if (nsl != null && nsl.Count > 0)
            {
                foreach (XmlNode attrNode in nsl)
                {
                    if (!doc.DocumentElement.HasAttribute(attrNode.Name))
                    {
                        doc.DocumentElement.SetAttribute(attrNode.Name, attrNode.Value);
                    }
                }
            }

            transform.LoadInput(doc);
            using (var stream = (Stream)transform.GetOutput(typeof(Stream)))
            {
                using (var reader = new StreamReader(stream))
                {
                    sb.Append(reader.ReadToEnd());
                }
            }

            return(sb.ToString());
        }
        public static Stream GetCanonicalStreamFromXML(XmlDocument xmlDoc)  //C14N
        {
            XmlDsigC14NTransform transformData = new XmlDsigC14NTransform();

            transformData.LoadInput(xmlDoc);
            return((Stream)transformData.GetOutput(typeof(Stream)));
        }
Ejemplo n.º 6
0
        private byte[] CanonicalizeAndDigest(IEnumerable nodes)
        {
            var transform = new XmlDsigC14NTransform {
                Algorithm = CanonicalizationAlgorithm
            };

            var sb = new StringBuilder();

            foreach (XmlNode node in nodes)
            {
                var tmpDoc = new XmlDocument();
                tmpDoc.AppendChild(tmpDoc.ImportNode(node, true));
                transform.LoadInput(tmpDoc);
                using (var stream = (Stream)transform.GetOutput(typeof(Stream)))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        sb.Append(reader.ReadToEnd());
                    }
                }
            }

            using (var hash = SHA256.Create())
            {
                return(hash.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString())));
            }
        }
Ejemplo n.º 7
0
        private static byte[] CalculateC14nByteRange(XmlDocument doc)
        {
            XmlDsigC14NTransform c14nTransform = new XmlDsigC14NTransform();

            c14nTransform.LoadInput(doc);
            return(((System.IO.MemoryStream)c14nTransform.GetOutput()).ToArray());
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Devuelve el XML de entrada canonicalizado.
        /// </summary>
        /// <param name="xmlContent">XML a canonicalizar.</param>
        /// <param name="xpath">Expresión XPath que devuelve el nodeList a canonicalizar.</param>
        /// <param name="namespaces">Espacios de nombres.</param>
        /// <returns>XML de entrada canonicalizado.</returns>
        public string GetCanonicalString(string xmlContent, string xpath, Dictionary <string, string> namespaces = null)
        {
            XmlDocument xmlDoc = new XmlDocument
            {
                PreserveWhitespace = true
            };

            xmlDoc.LoadXml(xmlContent);

            XmlNamespaceManager nm = new XmlNamespaceManager(xmlDoc.NameTable);

            var nms = namespaces ?? Namespaces.Items;

            foreach (KeyValuePair <string, string> n in nms)
            {
                nm.AddNamespace(n.Key, n.Value);
            }

            XmlNodeList xmlSignedProperties = xmlDoc.SelectNodes(xpath, nm);

            XmlDsigC14NTransform xmlTransform = new XmlDsigC14NTransform();

            xmlTransform.LoadInput(xmlSignedProperties);
            MemoryStream ms = (MemoryStream)xmlTransform.GetOutput(typeof(MemoryStream));

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
    public static void SignEnveloped(XmlDocument xmlDoc, RSACryptoServiceProvider key, string signatureNamespacePrefix)
    {
        SignedXml signedXml = new SignedXml(xmlDoc);

        signedXml.SigningKey = key;
        Reference reference = new Reference("");

        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        signedXml.AddReference(reference);
        signedXml.ComputeSignature();
        XmlElement xmlSignature = signedXml.GetXml();

        if (!string.IsNullOrEmpty(signatureNamespacePrefix))
        {
            //Here we set the namespace prefix on the signature element and all child elements to "ds", invalidating the signature.
            AssignNameSpacePrefixToElementTree(xmlSignature, "ds");
            //So let's recompute the SignatureValue based on our new SignatureInfo...
            //For XPath
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
            namespaceManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");     //this prefix is arbitrary and used only for XPath
            XmlElement xmlSignedInfo = xmlSignature.SelectSingleNode("ds:SignedInfo", namespaceManager) as XmlElement;
            //Canonicalize the SignedInfo element
            XmlDsigC14NTransform transform     = new XmlDsigC14NTransform();
            XmlDocument          signedInfoDoc = new XmlDocument();
            signedInfoDoc.LoadXml(xmlSignedInfo.OuterXml);
            transform.LoadInput(signedInfoDoc);
            //Compute the new SignatureValue
            string signatureValue = Convert.ToBase64String(key.SignData(transform.GetOutput() as MemoryStream, new SHA1CryptoServiceProvider()));
            //Set it in the xml
            XmlElement xmlSignatureValue = xmlSignature.SelectSingleNode("ds:SignatureValue", namespaceManager) as XmlElement;
            xmlSignatureValue.InnerText = signatureValue;
        }
        xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlSignature, true));
    }
Ejemplo n.º 10
0
        public void UnsupportedOutput()
        {
            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            XmlDocument          doc       = new XmlDocument();

            AssertExtensions.Throws <ArgumentException>("type", () => transform.GetOutput(doc.GetType()));
        }
    public static void Main(String[] args)
    {
        //calculate caninicalized xml

        var         t   = new XmlDsigEnvelopedSignatureTransform(false);
        XmlDocument doc = new XmlDocument();

        //doc.PreserveWhitespace = true;
        doc.Load(@"c:\temp\x.xml");
        t.LoadInput(doc);


        FieldInfo field = t.GetType().GetField("_signaturePosition",
                                               BindingFlags.NonPublic |
                                               BindingFlags.Instance);


        field.SetValue(t, 1);

        var res = (XmlDocument)t.GetOutput();
        var s   = res.OuterXml;

        var c14 = new XmlDsigC14NTransform();

        c14.LoadInput(res);
        var mem = (MemoryStream)c14.GetOutput();

        var sha = new SHA256Managed();

        var byte1   = c14.GetDigestedOutput(new SHA256Managed());
        var digest1 = Convert.ToBase64String(byte1);
        var byte2   = sha.ComputeHash(mem.ToArray());
        var digest2 = Convert.ToBase64String(byte2);


        var s1      = System.Text.Encoding.UTF8.GetString(mem.ToArray());
        var byte3   = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(s1));
        var digest3 = Convert.ToBase64String(byte3);

        //return;



        //validate signature

        CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.Load(@"c:\temp\x.xml");
        XmlNode          node    = xmlDoc.DocumentElement;
        X509Certificate2 cert    = new X509Certificate2(File.ReadAllBytes(@"c:\temp\x.cer"));
        bool             isValid = ValidateXml(xmlDoc, cert);
        //return;


        //calc hash
        var sha1 = new SHA256Managed();
        var b1   = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(@"c:\temp\x_no_sig.xml")));
        var b64  = Convert.ToBase64String(b1);
    }
Ejemplo n.º 12
0
        public static void Acc()
        {
            string      path = @"C:\Users\Tina\Documents\Visual Studio 2015\Projects\Document\XMLFile2.xml";
            XmlDocument xDoc = new XmlDocument();

            xDoc.PreserveWhitespace = true;
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                xDoc.Load(fs);
            }

            // canon node list
            // XmlNodeList nodeList = xDoc.SelectNodes("//Child1");
            XmlNodeList nodeList =
                xDoc.SelectNodes("//Child1/descendant-or-self::node()|//Child1//@*");
            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();

            transform.LoadInput(nodeList);
            MemoryStream ms = (MemoryStream)transform.GetOutput(typeof(Stream));
            string       cc = xDoc.InnerXml;

            File.WriteAllBytes(@"C:\Users\Tina\Documents\Visual Studio 2015\Projects\Document\child1.xml", ms.ToArray());

            // canon XMLDocument
            transform = new XmlDsigC14NTransform();
            transform.LoadInput(xDoc);
            ms = (MemoryStream)transform.GetOutput(typeof(Stream));

            // File.WriteAllBytes(@"C:\Users\Tina\Documents\Visual Studio 2015\Projects\Document\doc.xml", ms.ToArray());

            StreamReader reader = new StreamReader(ms);
            string       text   = reader.ReadToEnd();

            // Document to Stream
            ms = new MemoryStream();
            XmlWriter xw = XmlWriter.Create(ms);

            xDoc.WriteTo(xw);
            xw.Flush();
            ms.Position = 0;

            transform = new XmlDsigC14NTransform();
            transform.LoadInput(ms);
            ms = (MemoryStream)transform.GetOutput(typeof(Stream));

            File.WriteAllBytes(@"C:\Users\Tina\Documents\Visual Studio 2015\Projects\Document\ms.xml", ms.ToArray());

            // node to stream
            //ms = new MemoryStream();
            //xw = XmlWriter.Create(ms);
            //nodeList[0].WriteTo(xw);
            //xw.Flush();
            //ms.Position = 0;

            //transform = new XmlDsigC14NTransform();
            //transform.LoadInput(ms);
            //ms = (MemoryStream)transform.GetOutput(typeof(Stream));

            //File.WriteAllBytes(@"D:\Test\xml imza\ms2.xml", ms.ToArray());
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Canonicaliza el DTE sin el CAF. Luego agrega el CAF del xml original sin modificarlo.
        /// </summary>
        /// <param name="sDte"></param>
        /// <param name="ts"></param>
        public void Canonicaliza(string sDte, DateTime ts)
        {
            try
            {
                sMsj = string.Empty;
                iErr = 0;

                //Eliminar CAF de TED para que no sea canonicalizado
                XmlNode _xmlNode = modeloTed.xDocXml.SelectSingleNode("//TED/DD/CAF");
                _xmlNode.ParentNode.RemoveChild(_xmlNode);

                //Agrega TED a DTE/Documento
                XmlDocument xDte = new XmlDocument();
                xDte.PreserveWhitespace = true;
                xDte.LoadXml(Comun.Utiles.RemoveAllXmlNamespace(sDte));
                XmlDocumentFragment tedFragment = xDte.CreateDocumentFragment();
                tedFragment.InnerXml = modeloTed.xDocXml.DocumentElement.SelectSingleNode("//TED").OuterXml;
                xDte.DocumentElement.FirstChild.AppendChild(tedFragment);

                //Agregar TmstFirma
                XmlDocumentFragment timeStamp = xDte.CreateDocumentFragment();
                timeStamp.InnerXml = "<TmstFirma>" + ts.ToString("s") + "</TmstFirma>";
                xDte.DocumentElement.FirstChild.AppendChild(timeStamp);

                //Canonicalizar. Comenta para set de pruebas
                XmlDsigC14NTransform t = new XmlDsigC14NTransform();
                t.LoadInput(xDte);
                Stream s = (Stream)t.GetOutput(typeof(Stream));
                _xDocXml.Load(s);

                string sDocXml = _xDocXml.OuterXml.Replace("><", ">\n<");   //agrega line breaks
                //string sDocXml = xDte.OuterXml.Replace("><", ">\n<");   //agrega line breaks
                //string sDocXml = xDte.OuterXml;
                _xDocXml.LoadXml(sDocXml);

                //Agregar CAF
                XmlDocumentFragment caf = _xDocXml.CreateDocumentFragment();
                caf.InnerXml = _autorizacionXml.DocumentElement.SelectSingleNode("//AUTORIZACION/CAF").OuterXml;
                XmlNode it1    = _xDocXml.DocumentElement.SelectSingleNode("//DTE/Documento/TED/DD/IT1");
                XmlNode parent = _xDocXml.DocumentElement.SelectSingleNode("//DTE/Documento/TED/DD");
                parent.InsertAfter(caf, it1);

                //XmlNode caf = _autorizacionXml.DocumentElement.SelectSingleNode("//AUTORIZACION/CAF");
                //XmlNode it1 = _xDocXml.DocumentElement.SelectSingleNode("//DTE/Documento/TED/DD/IT1");
                //XmlNode parent = _xDocXml.DocumentElement.SelectSingleNode("//DTE/Documento/TED/DD");
                //parent.InsertAfter(caf, it1);

                sDocXml = _xDocXml.OuterXml.Replace("</IT1>", "</IT1>\n");  //agrega line break
                //sDocXml = _xDocXml.OuterXml;

                _xDocXml.LoadXml(sDocXml);
            }
            catch (Exception cn)
            {
                iErr++;
                sMsj = cn.Message + " [DteModel.Canonicaliza]";
                throw;
            }
        }
Ejemplo n.º 14
0
        private static string GetIRMark(byte[] Xml)
        {
            string vbLf   = "\n";
            string vbCrLf = "\r\n";

            //  Convert Byte array to string
            string      text = Encoding.UTF8.GetString(Xml);
            XmlDocument doc  = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(text);

            XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);

            ns.AddNamespace("env", doc.DocumentElement.NamespaceURI);
            XmlNode Body = doc.SelectSingleNode("//env:Body", ns);

            ns.AddNamespace("tax", Body.FirstChild.NamespaceURI);

            //   Create an XML document of just the body section
            XmlDocument xmlBody = new XmlDocument();

            xmlBody.PreserveWhitespace = true;
            xmlBody.LoadXml(Body.OuterXml);

            //  Remove any existing IRMark
            XmlNode nodeIr = xmlBody.SelectSingleNode("//tax:IRmark", ns);

            if (nodeIr != null)
            {
                nodeIr.ParentNode.RemoveChild(nodeIr);
            }

            //Normalise the document using C14N(Canonicalisation)
            XmlDsigC14NTransform c14n = new XmlDsigC14NTransform();

            c14n.LoadInput(xmlBody);

            using (Stream S = (Stream)c14n.GetOutput())
            {
                byte[] Buffer = new byte[S.Length];

                //  Convert to string and normalise line endings
                S.Read(Buffer, 0, (int)S.Length);
                text = Encoding.UTF8.GetString(Buffer);
                text = text.Replace("&#xD;", "");
                text = text.Replace(vbCrLf, vbLf);
                text = text.Replace(vbCrLf, vbLf);

                //   Convert the final document back into a byte array
                byte[] b = Encoding.UTF8.GetBytes(text);

                //   Create the SHA - 1 hash from the final document
                SHA1   SHA  = SHA1.Create();
                byte[] hash = SHA.ComputeHash(b);
                return(Convert.ToBase64String(hash));
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Devuelve el XML de entrada canonicalizado.
        /// </summary>
        /// <param name="xmlNodeList">Lista de nodos a canonicalizar.</param>
        /// <returns>XML de entrada canonicalizado.</returns>
        public string GetCanonicalString(XmlNodeList xmlNodeList)
        {
            XmlDsigC14NTransform xmlTransform = new XmlDsigC14NTransform();

            xmlTransform.LoadInput(xmlNodeList);
            MemoryStream ms = (MemoryStream)xmlTransform.GetOutput(typeof(MemoryStream));

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
Ejemplo n.º 16
0
        public void LoadInputAsXmlDocument()
        {
            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            XmlDocument          doc       = GetDoc();

            transform.LoadInput(doc);
            Stream s      = (Stream)transform.GetOutput();
            string output = TestHelpers.StreamToString(s, Encoding.UTF8);

            Assert.Equal(c14xml3, output);
        }
Ejemplo n.º 17
0
        internal static XmlDocument Canonize(XmlDocument doc)
        {
            XmlDsigC14NTransform t = new XmlDsigC14NTransform();

            t.LoadInput(doc);
            Stream       s      = (Stream)t.GetOutput(typeof(Stream));
            StreamReader reader = new StreamReader(s);

            doc.LoadXml(reader.ReadToEnd());
            return(doc);
        }
Ejemplo n.º 18
0
        public void LoadInputAsXmlNodeList()
        {
            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            XmlDocument          doc       = GetDoc();

            transform.LoadInput(doc.ChildNodes);
            Stream s      = (Stream)transform.GetOutput();
            string output = TestHelpers.StreamToString(s, Encoding.UTF8);

            Assert.Equal(@"<Test xmlns=""http://www.go-mono.com/""></Test>", output);
        }
Ejemplo n.º 19
0
        // MS has a bug that those namespace declaration nodes in
        // the node-set are written to output. Related spec section is:
        // http://www.w3.org/TR/2001/REC-xml-c14n-20010315#ProcessingModel
        public void LoadInputAsXmlNodeList2()
        {
            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            XmlDocument          doc       = GetDoc();

            transform.LoadInput(doc.SelectNodes("//*"));
            Stream s        = (Stream)transform.GetOutput();
            string output   = TestHelpers.StreamToString(s, Encoding.UTF8);
            string expected = @"<Test xmlns=""http://www.go-mono.com/""><Toto></Toto></Test>";

            Assert.Equal(expected, output);
        }
Ejemplo n.º 20
0
        private static byte[] CalculateC14nByteRange(XmlElement element, XmlDocument doc)
        {
            XmlElement cloneElement = (XmlElement)element.CloneNode(true);

            NormalizeNamespaces(element.CreateNavigator(), cloneElement.CreateNavigator());
            XmlDocument elememntDoc = new XmlDocument(doc.NameTable);

            elememntDoc.LoadXml(cloneElement.OuterXml);
            XmlDsigC14NTransform c14nTransform = new XmlDsigC14NTransform();

            c14nTransform.LoadInput(elememntDoc);
            return(((MemoryStream)c14nTransform.GetOutput()).ToArray());
        }
Ejemplo n.º 21
0
        public static byte[] CanonicalizeXml(XmlNode xmlNode)
        {
            XmlDocument manifestDoc = new XmlDocument();

            manifestDoc.PreserveWhitespace = true;
            manifestDoc.LoadXml(xmlNode.OuterXml);

            XmlDsigC14NTransform c14n = new XmlDsigC14NTransform(false);

            c14n.LoadInput(manifestDoc);

            return(((MemoryStream)c14n.GetOutput()).ToArray());
        }
    public static void Main(String[] args)
    {
        //calculate caninicalized xml

        var t = new XmlDsigEnvelopedSignatureTransform(false);
        XmlDocument doc = new XmlDocument();
        //doc.PreserveWhitespace = true;
        doc.Load(@"c:\temp\x.xml");
        t.LoadInput(doc);

        FieldInfo field = t.GetType().GetField("_signaturePosition",
                         BindingFlags.NonPublic |
                         BindingFlags.Instance);

        field.SetValue(t, 1);

        var res = (XmlDocument)t.GetOutput();
        var s = res.OuterXml;

        var c14 = new XmlDsigC14NTransform();
        c14.LoadInput(res);
        var mem = (MemoryStream)c14.GetOutput();

        var sha = new SHA256Managed();

        var byte1 = c14.GetDigestedOutput(new SHA256Managed());
        var digest1 = Convert.ToBase64String(byte1);
        var byte2 = sha.ComputeHash(mem.ToArray());
        var digest2 = Convert.ToBase64String(byte2);

        var s1 = System.Text.Encoding.UTF8.GetString(mem.ToArray());
        var byte3 = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(s1));
        var digest3 = Convert.ToBase64String(byte3);

        //return;

        //validate signature

        CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"c:\temp\x.xml");
        XmlNode node = xmlDoc.DocumentElement;
        X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(@"c:\temp\x.cer"));
        bool isValid = ValidateXml(xmlDoc, cert);
        //return;

        //calc hash
        var sha1 = new SHA256Managed();
        var b1 = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(@"c:\temp\x_no_sig.xml")));
        var b64 = Convert.ToBase64String(b1);
    }
Ejemplo n.º 23
0
        public void OrdinalSortForAttributes()
        {
            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            XmlDocument          doc       = new XmlDocument();
            string xml = "<foo Aa=\"one\" Bb=\"two\" aa=\"three\" bb=\"four\"><bar></bar></foo>";

            doc.LoadXml(xml);

            transform.LoadInput(doc);
            Stream s      = (Stream)transform.GetOutput();
            string output = TestHelpers.StreamToString(s, Encoding.UTF8);

            Assert.Equal(xml, output);
        }
Ejemplo n.º 24
0
        public void LoadInputAsStream()
        {
            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            MemoryStream         ms        = new MemoryStream();

            byte[] x = Encoding.ASCII.GetBytes(xml);
            ms.Write(x, 0, x.Length);
            ms.Position = 0;
            transform.LoadInput(ms);
            Stream s      = (Stream)transform.GetOutput();
            string output = TestHelpers.StreamToString(s, Encoding.UTF8);

            Assert.Equal(c14xml2, output);
        }
        private static byte[] GetXmlHashByteStream(XmlDocument xmlDoc)
        {
            byte[] hash;
            XmlDsigC14NTransform transformer = new XmlDsigC14NTransform();

            transformer.LoadInput(xmlDoc);
            using (Stream stream = (Stream)transformer.GetOutput(typeof(Stream)))
            {
                SHA1 sha1 = SHA1.Create();
                hash = sha1.ComputeHash(stream);
                stream.Close();
            }
            return(hash);
        }
Ejemplo n.º 26
0
        public void PrefixlessNamespaceOutput()
        {
            XmlDocument doc = new XmlDocument();

            doc.AppendChild(doc.CreateElement("foo", "urn:foo"));
            doc.DocumentElement.AppendChild(doc.CreateElement("bar", "urn:bar"));
            Assert.Equal(string.Empty, doc.DocumentElement.GetAttribute("xmlns"));
            XmlDsigC14NTransform t = new XmlDsigC14NTransform();

            t.LoadInput(doc);
            Stream s = t.GetOutput() as Stream;

            Assert.Equal("<foo xmlns=\"urn:foo\"><bar xmlns=\"urn:bar\"></bar></foo>", new StreamReader(s, Encoding.UTF8).ReadToEnd());
            Assert.Equal("urn:foo", doc.DocumentElement.GetAttribute("xmlns"));
        }
Ejemplo n.º 27
0
        public void SimpleNamespacePrefixes()
        {
            string input    = "<a:Action xmlns:a='urn:foo'>http://tempuri.org/IFoo/Echo</a:Action>";
            string expected = @"<a:Action xmlns:a=""urn:foo"">http://tempuri.org/IFoo/Echo</a:Action>";

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(input);
            XmlDsigC14NTransform t = new XmlDsigC14NTransform();

            t.LoadInput(doc);
            Stream s = t.GetOutput() as Stream;

            Assert.Equal(new StreamReader(s, Encoding.UTF8).ReadToEnd(), expected);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Serializa el objeto como xml y lo devuelve
        /// como archivo xml canonicalizado en una cadena.
        /// </summary>
        /// <param name="instance">Instancia de objeto a serializar.</param>
        /// <param name="namespaces">Espacios de nombres.</param>
        /// <param name="indent">Indica si se debe utilizar indentación.</param>
        /// <param name="omitXmlDeclaration">Indica si se se omite la delcaración xml.</param>
        /// <returns>string con el archivo xml.</returns>
        public string GetCanonicalString(object instance, Dictionary <string, string> namespaces, bool indent = false, bool omitXmlDeclaration = true)
        {
            var xmlContent = Encoding.GetString(GetBytes(instance, namespaces, indent, omitXmlDeclaration));

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xmlContent);

            XmlDsigC14NTransform xmlTransform = new XmlDsigC14NTransform();

            xmlTransform.LoadInput(xmlDoc);
            MemoryStream ms = (MemoryStream)xmlTransform.GetOutput(typeof(MemoryStream));

            return(Encoding.GetString(ms.ToArray()));
        }
Ejemplo n.º 29
0
        public static string GetCanonicalXml(string xml)
        {
            XmlDocument document = new XmlDocument();

            document.PreserveWhitespace = true;
            document.LoadXml(xml);

            XmlDsigC14NTransform c14n = new XmlDsigC14NTransform();

            c14n.LoadInput(document);

            Stream s = (Stream)c14n.GetOutput(typeof(Stream));

            return(new StreamReader(s, Encoding.UTF8).ReadToEnd());
        }
        private static Stream CanonicalizeNode(XmlNode node)
        {
            var       reader = new XmlNodeReader(node);
            Stream    stream = new MemoryStream();
            XmlWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            writer.WriteNode(reader, false);
            writer.Flush();

            stream.Position = 0;
            var transform = new XmlDsigC14NTransform();

            transform.LoadInput(stream);
            return((Stream)transform.GetOutput());
        }
Ejemplo n.º 31
0
        private static string GetDigest(XmlDocument doc)
        {
            XmlDsigC14NTransform t = new XmlDsigC14NTransform();

            t.LoadInput(doc);
            Stream s = (Stream)t.GetOutput(typeof(Stream));

            byte[] hash;

            using (SHA512 sha = new SHA512Managed())
            {
                hash = sha.ComputeHash(s);
            }

            return(Convert.ToBase64String(hash));
        }