Exemplo n.º 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);
         }
     }
 }
Exemplo n.º 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);
 }
Exemplo n.º 3
0
 private static byte[] CalculateC14nByteRange(XmlDocument doc) {
     XmlDsigC14NTransform c14nTransform = new XmlDsigC14NTransform();
     c14nTransform.LoadInput(doc);
     return ((MemoryStream)c14nTransform.GetOutput()).ToArray();
 }
Exemplo n.º 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();
 }
Exemplo n.º 5
0
		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");
		}
Exemplo n.º 6
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.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;
        }
Exemplo n.º 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;
		} 
Exemplo n.º 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);
         }
     }
 }
Exemplo n.º 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();
        }
Exemplo n.º 12
0
        private string dereferenceURI(XmlNode reference)
        {
            XmlAttribute uriAttr = (XmlAttribute)reference.Attributes.GetNamedItem("URI");
            string id = uriAttr.Value.Replace("#", "");

            if (id == "Signature20140325080345213SignatureProperties")
                id = id;

            XmlNode digestMethNode = reference.SelectSingleNode("ds:DigestMethod", xNS);
            XmlAttribute digestMethNode_alg = (XmlAttribute)digestMethNode.Attributes.GetNamedItem("Algorithm");
            string alg = digestMethNode_alg.Value;
            XmlNode digestValNode = reference.SelectSingleNode("ds:DigestValue", xNS);
            string digestValue = digestValNode.InnerText;

            //ak ide o manifest -> kanonikalizacia a overenie odtlacku
            if (id.StartsWith("ManifestObject"))
            {
                XmlNode manifestNode = xSignature.SelectSingleNode("//ds:Manifest[@Id='" + id + "']", xNS);
                string s = manifestNode.OuterXml;

                // The XmlDsigC14NTranswill strip the UTF8 BOM
                using (MemoryStream msIn = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s)))
                {
                    XmlDsigC14NTransform t = new XmlDsigC14NTransform(true);
                    t.LoadInput(msIn);

                    HashAlgorithm hash = null;
                    switch (alg)
                    {
                        case "http://www.w3.org/2000/09/xmldsig#sha1":
                            hash = new System.Security.Cryptography.SHA1Managed();
                            break;
                        case "http://www.w3.org/2001/04/xmldsig-more#sha224":
                            //hash = new System.Security.Cryptography.SH();
                            break;
                        case "http://www.w3.org/2001/04/xmlenc#sha256":
                            hash = new System.Security.Cryptography.SHA256Managed();
                            break;
                        case "http://www.w3.org/2001/04/xmldsig-more#sha384":
                            hash = new System.Security.Cryptography.SHA384Managed();
                            break;
                        case "http://www.w3.org/2001/04/xmlenc#sha512":
                            hash = new System.Security.Cryptography.SHA512Managed();
                            break;
                    }

                    if (hash == null)
                        return "hash algorithm ERROR (" + alg + ")";

                    byte[] digest = t.GetDigestedOutput(hash);
                    //string result = BitConverter.ToString(digest).Replace("-", String.Empty);
                    string result = Convert.ToBase64String(digest);
                    if (result.Equals(digestValue))
                        return string.Empty;
                    else
                    {
                       return  "digest value ERROR";
                    }

                }
            }

            return string.Empty;

            //throw new NotImplementedException();
        }
Exemplo n.º 13
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);
        }