Example #1
0
 /// <summary>
 /// Compares all idml's in outputPath to make sure the content.xml and styles.xml are the same
 /// </summary>
 public static void AreEqual(string expectFullName, string outputFullName, string msg)
 {
     using (var expFl = new ZipFile(expectFullName))
     {
         var outFl = new ZipFile(outputFullName);                
         foreach (ZipEntry zipEntry in expFl)
         {
             //TODO: designmap.xml should be tested but \\MetadataPacketPreference should be ignored as it contains the creation date.
             if (!CheckFile(zipEntry.Name,"Stories,Spreads,Resources,MasterSpreads"))
                 continue;
             if (Path.GetExtension(zipEntry.Name) != ".xml")
                 continue;
             string outputEntry = new StreamReader(outFl.GetInputStream(outFl.GetEntry(zipEntry.Name).ZipFileIndex)).ReadToEnd();
             string expectEntry = new StreamReader(expFl.GetInputStream(expFl.GetEntry(zipEntry.Name).ZipFileIndex)).ReadToEnd();
             XmlDocument outputDocument = new XmlDocument();
             outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             outputDocument.LoadXml(outputEntry);
             XmlDocument expectDocument = new XmlDocument();
             outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             expectDocument.LoadXml(expectEntry);
             XmlDsigC14NTransform outputCanon = new XmlDsigC14NTransform();
             outputCanon.Resolver = new XmlUrlResolver();
             outputCanon.LoadInput(outputDocument);
             XmlDsigC14NTransform expectCanon = new XmlDsigC14NTransform();
             expectCanon.Resolver = new XmlUrlResolver();
             expectCanon.LoadInput(expectDocument);
             Stream outputStream = (Stream)outputCanon.GetOutput(typeof(Stream));
             Stream expectStream = (Stream)expectCanon.GetOutput(typeof(Stream));
             string errMessage = string.Format("{0}: {1} doesn't match", msg, zipEntry.Name);
             Assert.AreEqual(expectStream.Length, outputStream.Length, errMessage);
             FileAssert.AreEqual(expectStream, outputStream, errMessage);
         }
     }
 }
Example #2
0
 /// <summary>
 /// Compares the XML file at expected path tand output path to make sure they are the same in terms of what matters to XML.
 /// </summary>
 /// <param name="expectPath">expected output path</param>
 /// <param name="outputPath">output path</param>
 /// <param name="msg">message to display if mismatch</param>
 public static void AreEqual(string expectPath, string outputPath, string msg)
 {
     XmlDocument outputDocument = Common.DeclareXMLDocument(false);
     outputDocument.Load(outputPath);
     XmlDocument expectDocument = Common.DeclareXMLDocument(false);
     expectDocument.Load(expectPath);
     XmlDsigC14NTransform outputCanon = new XmlDsigC14NTransform();
     outputCanon.Resolver = null;
     outputCanon.LoadInput(outputDocument);
     XmlDsigC14NTransform expectCanon = new XmlDsigC14NTransform();
     expectCanon.Resolver = null;
     expectCanon.LoadInput(expectDocument);
     Stream outputStream = (Stream)outputCanon.GetOutput(typeof(Stream));
     Stream expectStream = (Stream)expectCanon.GetOutput(typeof(Stream));
     FileAssert.AreEqual(expectStream, outputStream, msg);
 }
Example #3
0
 private static byte[] CalculateC14nByteRange(XmlDocument doc) {
     XmlDsigC14NTransform c14nTransform = new XmlDsigC14NTransform();
     c14nTransform.LoadInput(doc);
     return ((MemoryStream)c14nTransform.GetOutput()).ToArray();
 }
Example #4
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();
 }
		public void PrefixlessNamespaceOutput ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.AppendChild (doc.CreateElement ("foo", "urn:foo"));
			doc.DocumentElement.AppendChild (doc.CreateElement ("bar", "urn:bar"));
			Assert.AreEqual (String.Empty, doc.DocumentElement.GetAttribute ("xmlns"), "#1");
			XmlDsigC14NTransform t = new XmlDsigC14NTransform ();
			t.LoadInput (doc);
			Stream s = t.GetOutput () as Stream;
			Assert.AreEqual (new StreamReader (s, Encoding.UTF8).ReadToEnd (), "<foo xmlns=\"urn:foo\"><bar xmlns=\"urn:bar\"></bar></foo>");
			Assert.AreEqual ("urn:foo", doc.DocumentElement.GetAttribute ("xmlns"), "#2");
		}
		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.AreEqual (new StreamReader (s, Encoding.UTF8).ReadToEnd (), expected);
		}
        public static Stream CanonicalizeNode(XmlNode node)
        {
            XmlNodeReader reader = new XmlNodeReader(node);
            Stream stream = new MemoryStream();
            XmlWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

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

            stream.Position = 0;
            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            transform.LoadInput(stream);
            return (Stream)transform.GetOutput();
        }
        /// <summary>
        /// Creates the Gateway IR Mark for the submission messages
        /// Derived from http://neophytedeveloper.wordpress.com/
        /// </summary>
        /// <param name="Xml">byte array of xml document</param>
        /// <param name="ofile">Name of destination file saved to disk</param>
        /// <returns></returns>
        public static string GetIRMark(byte[] Xml, string ofile)
        {
            string vbLf = "\n";
            string vbCrLf = "\r\n";
            string result = String.Empty;
            try
            {
                // Convert Byte array to string
                string text = Encoding.UTF8.GetString(Xml);

                //load new XmlDocument with xml text
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.LoadXml(text);

                XmlNode root = doc.DocumentElement;

                XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
                ns.AddNamespace("govtalkgateway", doc.DocumentElement.NamespaceURI);

                // Create an XML document of just the body section
                XmlNode Body = doc.SelectSingleNode("//govtalkgateway:Body", ns);

                ns.AddNamespace("ir68", Body.FirstChild.NextSibling.NamespaceURI);

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

                // Remove any existing IRMark
                XmlNode nodeIr = xmlBody.SelectSingleNode("//ir68:IRmark", ns);
                XmlNode IrMarkPlaceHolder = nodeIr;
                if (nodeIr != null)
                {
                    IrMarkPlaceHolder = nodeIr.PreviousSibling;
                    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);

                    result = Convert.ToBase64String(hash);
                }

                // attempt to re-insert the IRmark

                XmlNode IRmarkNode = root.SelectSingleNode("//*[contains(name(),'IRmark')]");

                if (!String.IsNullOrEmpty(IRmarkNode.InnerText))
                {
                    root.SelectSingleNode("//*[contains(name(),'IRmark')]").LastChild.Value = result;
                }
                else
                    if (root.SelectSingleNode("//*[contains(name(),'IRmark')]") != null)
                    {
                        IRmarkNode.InnerText = result;
                    }
                    else
                    {
                        log.Info("No IRmark");
                    }

                using (XmlTextWriter writer = new XmlTextWriter(ofile, null))
                {
                    // writer.Formatting = Formatting.Indented;
                    doc.Save(writer);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
            return result;
        }
Example #9
0
		public byte[] ComputeHashValueOfElementList(XmlElement signatureXmlElement, ArrayList elementXpaths, ref ArrayList elementIdValues)
		{
			XmlDocument xmlDocument;
			XmlNamespaceManager xmlNamespaceManager;
			XmlNodeList searchXmlNodeList;
			XmlElement composedXmlElement;
			XmlDsigC14NTransform xmlDsigC14NTransform;
			Stream canonicalizedStream;
			SHA1 sha1Managed;
			byte[] retVal;

			xmlDocument = signatureXmlElement.OwnerDocument;
			composedXmlElement = xmlDocument.CreateElement("ComposedElement", SignedXml.XmlDsigNamespaceUrl);
			xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
			xmlNamespaceManager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
			xmlNamespaceManager.AddNamespace("xsd", XadesSignedXml.XadesNamespaceUri);
			foreach (string elementXpath in elementXpaths)
			{
				searchXmlNodeList = signatureXmlElement.SelectNodes(elementXpath, xmlNamespaceManager);
				if (searchXmlNodeList.Count == 0)
				{
					throw new CryptographicException("Element " + elementXpath + " not found while calculating hash");
				}
				foreach (XmlNode xmlNode in searchXmlNodeList)
				{
					if (((XmlElement)xmlNode).HasAttribute("Id"))
					{
						elementIdValues.Add(((XmlElement)xmlNode).Attributes["Id"].Value);
						composedXmlElement.AppendChild(xmlNode);
					}
					else
					{
						throw new CryptographicException("Id attribute missing on " + xmlNode.LocalName + " element");
					}
				}
			}
			xmlDsigC14NTransform = new XmlDsigC14NTransform(false);
			xmlDsigC14NTransform.LoadInput(composedXmlElement.ChildNodes);
			canonicalizedStream = (Stream)xmlDsigC14NTransform.GetOutput(typeof(Stream));
			sha1Managed = new SHA1Managed();
			retVal = sha1Managed.ComputeHash(canonicalizedStream);
			canonicalizedStream.Close();

			return retVal;
		} 
Example #10
0
 /// <summary>
 /// Compares all odt's in outputPath to make sure the content.xml and styles.xml are the same
 /// </summary>
 /// <param name="expectPath">expected output path</param>
 /// <param name="outputPath">output path</param>
 /// <param name="msg">message to display if mismatch</param>
 public static void AreEqual(string expectPath, string outputPath, string msg)
 {
     var outDi = new DirectoryInfo(outputPath);
     var expDi = new DirectoryInfo(expectPath);
     FileInfo[] outFi = outDi.GetFiles("*.od*");
     FileInfo[] expFi = expDi.GetFiles("*.od*");
     Assert.AreEqual(outFi.Length, expFi.Length, string.Format("{0} {1} odt found {2} expected", msg, outFi.Length, expFi.Length));
     foreach (FileInfo fi in outFi)
     {
         var outFl = new ZipFile(fi.FullName);
         var expFl = new ZipFile(Common.PathCombine(expectPath, fi.Name));
         foreach (string name in "content.xml,styles.xml".Split(','))
         {
             string outputEntry = new StreamReader(outFl.GetInputStream(outFl.GetEntry(name).ZipFileIndex)).ReadToEnd();
             string expectEntry = new StreamReader(expFl.GetInputStream(expFl.GetEntry(name).ZipFileIndex)).ReadToEnd();
             XmlDocument outputDocument = new XmlDocument();
             outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             outputDocument.LoadXml(outputEntry);
             XmlDocument expectDocument = new XmlDocument();
             expectDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             expectDocument.LoadXml(expectEntry);
             XmlDsigC14NTransform outputCanon = new XmlDsigC14NTransform();
             outputCanon.Resolver = new XmlUrlResolver();
             outputCanon.LoadInput(outputDocument);
             XmlDsigC14NTransform expectCanon = new XmlDsigC14NTransform();
             expectCanon.Resolver = new XmlUrlResolver();
             expectCanon.LoadInput(expectDocument);
             Stream outputStream = (Stream)outputCanon.GetOutput(typeof(Stream));
             Stream expectStream = (Stream)expectCanon.GetOutput(typeof(Stream));
             string errMessage = string.Format("{0}: {1} {2} doesn't match", msg, fi.Name, name);
             Assert.AreEqual(expectStream.Length, outputStream.Length, errMessage);
             FileAssert.AreEqual(expectStream, outputStream, errMessage);
         }
     }
 }
Example #11
0
        private byte[] canonicalize(XmlNode outerData, string signedInfoTransformAlg)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(outerData.InnerXml);

            var data = doc.DocumentElement;

            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
            transform.Algorithm = signedInfoTransformAlg;
            transform.LoadInput(doc);// =  data;

            var a = transform.GetOutput();
            var aa = a.ToString();

            var b = a as System.IO.Stream;

            b.Position = 0;
            byte[] buffer = new byte[b.Length];
            for (int totalBytesCopied = 0; totalBytesCopied < b.Length;)
                totalBytesCopied += b.Read(buffer, totalBytesCopied, Convert.ToInt32(b.Length) - totalBytesCopied);
            return buffer;

            //return System.Text.Encoding.UTF8.GetBytes(aa);
            //XmlDsigExcC14NTransform.
            //System.Security.Cryptography
            throw new NotImplementedException();
        }
Example #12
0
        private string Canononicalize(XmlNode signedInfoN)
        {
            XmlNodeList signedInfoNodeList = signedInfoN.SelectNodes("//ds:SignedInfo", xNS);
            XmlNode signedInfoNode = signedInfoN.SelectSingleNode("//ds:SignedInfo", xNS);

            byte[] signatureCertificate = Convert.FromBase64String(signedInfoN.SelectSingleNode(@"//ds:KeyInfo/ds:X509Data/ds:X509Certificate",xNS).InnerText);
            byte[] signature = Convert.FromBase64String(signedInfoN.SelectSingleNode(@"//ds:SignatureValue", xNS).InnerText);

            XmlDsigC14NTransform t = new XmlDsigC14NTransform(false);
            XmlDocument pom = new XmlDocument();
            pom.LoadXml(signedInfoNode.OuterXml);
            t.LoadInput(pom);
            byte[] data = ((MemoryStream)t.GetOutput()).ToArray();

            string signedInfoTransformAlg = signedInfoNode.SelectSingleNode("ds:CanonicalizationMethod", xNS).Attributes.GetNamedItem("Algorithm").Value;
            string signedInfoSignatureAlg = signedInfoNode.SelectSingleNode("ds:SignatureMethod", xNS).Attributes.GetNamedItem("Algorithm").Value;

            return verifySign(signatureCertificate, signature, data, signedInfoSignatureAlg);
        }