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 static byte[] CanonicalizeXmlDigest(XmlNode xmlNode, System.Security.Cryptography.HashAlgorithm hashAlgo) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.LoadXml(xmlNode.OuterXml); XmlDsigC14NTransform c14n = new XmlDsigC14NTransform(false); c14n.LoadInput(xmlDoc); return(c14n.GetDigestedOutput(hashAlgo)); }
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()); }
private byte[] DoC14N_Xades(XmlDocument doc) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace(ns_etsi_prefix, ns_etsi_uri); XmlNode node1 = doc.SelectSingleNode(XPATH_XADES, nsmgr); XmlNodeList list = node1.SelectNodes("descendant-or-self::node()|//@*"); XmlDsigC14NTransform c14n = new XmlDsigC14NTransform(false); c14n.LoadInput(list); return(DoC14N(c14n)); }
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); }
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); }
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); }
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); }
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()); }
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")); }
/// <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())); }
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); }
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()); }
private static string Canonicalize(XmlNode input) { Assert.NotNull(input); var doc = new XmlDocument(); doc.LoadXml(input.OuterXml); var t = new XmlDsigC14NTransform(); t.LoadInput(doc); var stream = (Stream)t.GetOutput(typeof(Stream)); return(new StreamReader(stream).ReadToEnd()); }
/// <summary> /// Devuelve el XML de entrada canonicalizado. /// </summary> /// <param name="xmlContent">XML a canonicalizar.</param> /// <returns>XML de entrada canonicalizado.</returns> public string GetCanonicalString(string xmlContent) { XmlDocument xmlDoc = new XmlDocument { PreserveWhitespace = true }; xmlDoc.LoadXml(xmlContent); XmlDsigC14NTransform xmlTransform = new XmlDsigC14NTransform(); xmlTransform.LoadInput(xmlDoc); MemoryStream ms = (MemoryStream)xmlTransform.GetOutput(typeof(MemoryStream)); return(Encoding.GetString(ms.ToArray())); }
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)); }
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); }
public void Test(SignedXmlDocument doc) { Console.WriteLine("================== Certificate Test =================="); var certVipNet = doc.CertificateValue.Value; var result = doc.CertificateValue.Value == Convert.ToBase64String(Certificate.GetRawCertData()); Console.WriteLine("Test done: {0}", result); Console.WriteLine("======================================================"); Console.WriteLine("================ Canonicalization Test ================"); var doc2 = doc.Document.GetXmlDocument(); XmlDsigExcC14NTransform t = new XmlDsigExcC14NTransform(); var bodyNode = doc.Body.GetXmlNode(); t.LoadInput(bodyNode); Stream canonicalXmlStream = (MemoryStream)t.GetOutput(typeof(Stream)); var canonicalXml = new StreamReader(canonicalXmlStream).ReadToEnd(); var t2 = new XmlDsigC14NTransform(); t2.LoadInput(doc.Body.GetXmlNode()); Stream canonicalXmlStream2 = (MemoryStream)t2.GetOutput(typeof(Stream)); var canonicalXml2 = new StreamReader(canonicalXmlStream2).ReadToEnd(); Console.WriteLine(canonicalXml == canonicalXml2); Console.WriteLine(canonicalXml); Console.WriteLine("======================================================"); var signedXml = new SignedXml(doc2); var reference = new Reference("#body"); reference.AddTransform(new XmlDsigExcC14NTransform()); signedXml.AddReference(reference); Hash hash = new VipNetCrytoProvider().HashData(canonicalXml); Console.WriteLine(hash.Base64); Console.WriteLine(hash.Hex); Console.WriteLine("CorrectHashExample: {0}", CorrectHashExample); Console.WriteLine("CorrectHashExampleHex: {0}", Convert.FromBase64String(CorrectHashExample).ByteArrayToString()); }
/// <summary> /// Gets the normalized XML string. /// </summary> /// <param name="element">The XElement.</param> /// <returns>Returns the normalized xml string.</returns> private static string GetNormalizedXmlString(XElement element) { string xmlLiteralValue = element.ToString(); if (element != null) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlLiteralValue); XmlDsigC14NTransform t2 = new XmlDsigC14NTransform(); t2.LoadInput(xmlDoc); var w = t2.GetOutput() as MemoryStream; byte[] buffer = new byte[w.Length]; w.Read(buffer, 0, (int)w.Length); xmlLiteralValue = System.Text.Encoding.Default.GetString(buffer); } return(xmlLiteralValue); }
/// <summary> /// Load input nodes to process /// </summary> public override void LoadInput(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } // Canonicalize the input into a stream XmlDsigC14NTransform canonicalization = new XmlDsigC14NTransform(true); canonicalization.LoadInput(obj); Stream canonicalizedInput = canonicalization.GetOutput(typeof(Stream)) as Stream; // Load the canonicalized input into a document to transform XmlDocument document = new XmlDocument(); document.Load(canonicalizedInput); m_inputNodes = document; }
/// <summary> /// Generate the IRMark from XmlDocument object /// </summary> /// <param name="xmlDocument">XmlDocument object</param> /// <returns>IRMark</returns> public async Task <string> Generate(XmlDocument xmlDocument) { var result = ""; var c14N = new XmlDsigC14NTransform(); c14N.LoadInput(xmlDocument); using (MemoryStream stream = (MemoryStream)c14N.GetOutput()) { var msBytes = stream.ToArray(); var sha1 = SHA1.Create(); var hashBytes = sha1.ComputeHash(msBytes); result = Convert.ToBase64String(hashBytes); } return(result); }
internal MemoryStream method_0(Stream A_0) { int num = 6; MemoryStream outStream = null; A_0.Position = 0L; switch (this.transformType_0) { case TransformType.C14n: { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); transform.LoadInput(A_0); return((MemoryStream)transform.GetOutput(typeof(MemoryStream))); } case TransformType.Relationship: { XmlDocument document = this.method_1(A_0); A_0.Position = 0L; XmlDocument document2 = this.method_1(A_0); XmlNode node = document2.GetElementsByTagName(BookmarkStart.b("縫䬭尯匱䀳張圷吹伻嘽⤿㉁㝃", num))[0]; node.RemoveAll(); using (IEnumerator enumerator = this.class740_0.System.Collections.IEnumerable.GetEnumerator()) { while (enumerator.MoveNext()) { string current = (string)enumerator.Current; XmlNode node2 = document.SelectSingleNode(string.Format(BookmarkStart.b("̫ĭᨯ椱琳缵尷ܹᬻ䔽瀿㽁捃ᭅ", num), current)); XmlAttribute attribute = node2.OwnerDocument.CreateAttribute(BookmarkStart.b("砫伭䈯唱儳䈵男唹堻嬽", num)); attribute.Value = BookmarkStart.b("攫䀭䐯圱䘳堵夷嘹", num); node2.Attributes.Append(attribute); XmlNode newChild = document2.ImportNode(node2, true); node.AppendChild(newChild); } } outStream = new MemoryStream(); document2.Save(outStream); return(outStream); } } return(outStream); }
/// <summary> /// Vytvoří autentitační token pro volání služby /// </summary> /// <param name="key">Přístupový klíč</param> /// <param name="request">Request služby včetně elementu <SOAP:Envelope></SOAP:Envelope></param> /// <returns></returns> private static string _sign(string key, string request) { //z request se vytvoří XmlDocument XmlDocument xmlRequest = new XmlDocument(); xmlRequest.LoadXml(request); //spočítá se SHA1 hash přístupového klíče SHA1 sha1 = SHA1.Create(); byte[] hashKey = sha1.ComputeHash(Encoding.UTF8.GetBytes(key)); //z requestu se vytáhne element body včetně krajních XML značek - outer xml XmlDocument xmlBody = new XmlDocument(); xmlBody.LoadXml(xmlRequest.GetElementsByTagName("Body", xmlRequest.DocumentElement.NamespaceURI)[0].OuterXml); //provede se kanonizace body XmlDsigC14NTransform tr = new XmlDsigC14NTransform(); tr.LoadInput(xmlBody); MemoryStream transOutput = (MemoryStream)tr.GetOutput(); byte[] bodyBytes = transOutput.ToArray();; //ke kanonizovanému body se bytově připojí SHA1 hash hesla byte[] combined = new byte[bodyBytes.Length + hashKey.Length]; System.Buffer.BlockCopy(bodyBytes, 0, combined, 0, bodyBytes.Length); System.Buffer.BlockCopy(hashKey, 0, combined, bodyBytes.Length, hashKey.Length); //výsledek se zahashuje SHA512 SHA512 sha512 = SHA512.Create(); byte[] hashResult = sha512.ComputeHash(combined); //převede se do base64 string result = Convert.ToBase64String(hashResult); return(result); }
byte[] CanonicalizeAndDigest(XmlNodeList nodeList, bool dotraverser = true) { var encoding = System.Text.Encoding.UTF8; var transform = new XmlDsigC14NTransform(); var outersb = new StringBuilder(); foreach (XmlNode n in nodeList) { var newdoc = new XmlDocument { PreserveWhitespace = true }; var newnode = newdoc.AppendChild(newdoc.ImportNode(n, true)); var traverser = n.ParentNode; while (dotraverser && traverser != null) { if (traverser.Attributes != null) { foreach (var a in traverser.Attributes.OfType <XmlAttribute>()) { if (a.Name.StartsWith("xmlns")) { var newattrivute = (XmlAttribute)newdoc.ImportNode(a, true); newnode.Attributes.Append(newattrivute); } } } traverser = traverser.ParentNode; } var sb = new StringBuilder(); sb.Append(newnode.OuterXml); using (var transformerinput = new MemoryStream(encoding.GetBytes(sb.ToString()))) { transform.LoadInput(transformerinput); using (var o = transform.GetOutput() as MemoryStream) outersb.Append(encoding.GetString(o.ToArray())); } } return(SHA256.Create().ComputeHash(encoding.GetBytes(outersb.ToString()))); }
/// <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); } } }
/// <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 = new XmlDocument(); outputDocument.Load(outputPath); RemoveTextNl(outputDocument); //Linux adds \n into serialized output XmlDocument expectDocument = new XmlDocument(); expectDocument.Load(expectPath); RemoveTextNl(expectDocument); //Linux adds \n into serialized output 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); }
private Stream CanonicalizeElement(XmlElement element, out string canonicalizationMethodUri, Action <string> setCanonicalization = null) { //The canonicalization transformer can't reasonable do just an element. It //seems content to do an entire XmlDocument. var transformer = new XmlDsigC14NTransform(false); setCanonicalization?.Invoke(transformer.Algorithm); var newDocument = new XmlDocument(_document.NameTable); newDocument.LoadXml(element.OuterXml); transformer.LoadInput(newDocument); var result = transformer.GetOutput(typeof(Stream)); canonicalizationMethodUri = transformer.Algorithm; if (result is Stream s) { return(s); } throw new NotSupportedException("Unable to canonicalize element."); }
/// <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); } } }
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()) { // var ss = new StreamReader(S).ReadToEnd(); // Console.WriteLine(ss); // Console.ReadLine(); 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("
", ""); 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); //var hasher = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha1); //byte[] hash = hasher.HashData(b); return(Convert.ToBase64String(hash)); } }
// Encrypt the text in the specified XmlDocument. private static void ShowTransformProperties(XmlDocument xmlDoc) { //<Snippet1> XmlDsigC14NTransform xmlTransform = new XmlDsigC14NTransform(true); //</Snippet1> // Ensure the transform is using the appropriate algorithm. //<Snippet4> xmlTransform.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl; //</Snippet4> // Retrieve the XML representation of the current transform. //<Snippet10> XmlElement xmlInTransform = xmlTransform.GetXml(); //</Snippet10> Console.WriteLine("\nXml representation of the current transform: "); Console.WriteLine(xmlInTransform.OuterXml); // Retrieve the valid input types for the current transform. //<Snippet5> Type[] validInTypes = xmlTransform.InputTypes; //</Snippet5> // Verify the xmlTransform can accept the XMLDocument as an // input type. for (int i = 0; i < validInTypes.Length; i++) { if (validInTypes[i] == xmlDoc.GetType()) { // Load the document into the transfrom. //<Snippet12> xmlTransform.LoadInput(xmlDoc); //</Snippet12> //<Snippet3> XmlDsigC14NTransform secondTransform = new XmlDsigC14NTransform(); //</Snippet3> //<Snippet13> string classDescription = secondTransform.ToString(); //</Snippet13> // This call does not perform as expected. // This transform does not contain inner XML elements //<Snippet11> secondTransform.LoadInnerXml(xmlDoc.SelectNodes("//.")); //</Snippet11> break; } } //<Snippet6> Type[] validOutTypes = xmlTransform.OutputTypes; //</Snippet6> for (int i = 0; i < validOutTypes.Length; i++) { if (validOutTypes[i] == typeof(System.IO.Stream)) { try { //<Snippet9> Type streamType = typeof(System.IO.Stream); MemoryStream outputStream = (MemoryStream) xmlTransform.GetOutput(streamType); //</Snippet9> // Read the CryptoStream into a stream reader. StreamReader streamReader = new StreamReader(outputStream); // Read the stream into a string. string outputMessage = streamReader.ReadToEnd(); // Close the streams. outputStream.Close(); streamReader.Close(); // Display to the console the Xml before and after // encryption. Console.WriteLine("Encoding the following xml: " + xmlDoc.OuterXml); Console.WriteLine("Message encoded: " + outputMessage); } catch (Exception ex) { Console.WriteLine("Unexpected exception caught: " + ex.ToString()); } break; } else { //<Snippet8> object outputObject = xmlTransform.GetOutput(); //</Snippet8> } } }
private string step_3(string filename) //Core validation { string[] SUPPORTED_TRANSFORMS = { "http://www.w3.org/TR/2001/REC-xml-c14n-20010315", "http://www.w3.org/2000/09/xmldsig#base64", }; string[] SUPPORTED_DIGEST_METHOD = { "http://www.w3.org/2001/04/xmlenc#sha512 ", "http://www.w3.org/2001/04/xmldsig-more#sha384", "http://www.w3.org/2001/04/xmlenc#sha256", "http://www.w3.org/2001/04/xmldsig-more#sha224", "http://www.w3.org/2000/09/xmldsig#sha1", }; XmlDocument xades = new XmlDocument(); xades.Load(filename); var namespaceId = new XmlNamespaceManager(xades.NameTable); namespaceId.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); namespaceId.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#"); //check ds:SignedInfo and ds:Manifest XmlNode signedInfoN = xades.SelectSingleNode(@"//ds:SignedInfo", namespaceId); XmlNodeList referenceElements = signedInfoN.SelectNodes(@"//ds:Reference", namespaceId); //Reference in SignedInfo foreach (XmlNode reference in referenceElements) { String ReferenceURI = reference.Attributes.GetNamedItem("URI").Value; ReferenceURI = ReferenceURI.Substring(1); XmlNode digestMethod = reference.SelectSingleNode("ds:DigestMethod", namespaceId); String digestMethodAlgorithm = digestMethod.Attributes.GetNamedItem("Algorithm").Value; string dsDigestValue = reference.SelectSingleNode("ds:DigestValue", namespaceId).InnerText; if (ReferenceURI.StartsWith("ManifestObject")) { //get Manifest XML and check DigestValue string manifestXML = xades.SelectSingleNode("//ds:Manifest[@Id='" + ReferenceURI + "']", namespaceId).OuterXml; MemoryStream sManifest = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(manifestXML)); XmlDsigC14NTransform t = new XmlDsigC14NTransform(); t.LoadInput(sManifest); HashAlgorithm hash = null; switch (digestMethodAlgorithm) { case "http://www.w3.org/2000/09/xmldsig#sha1": hash = new System.Security.Cryptography.SHA1Managed(); 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("nesprávny hashovací algoritmus " + digestMethodAlgorithm); } byte[] digest = t.GetDigestedOutput(hash); string result = Convert.ToBase64String(digest); Console.WriteLine("-"); Console.WriteLine("Overenie hodnoty podpisu"); Console.WriteLine(result); Console.WriteLine(dsDigestValue); Console.WriteLine("-"); if (!result.Equals(dsDigestValue)) { return("hodnoty DigestValue s výpočtom Manifest sa nezhodujú"); } } } //signed info kanonikalizovat XmlNode checkData = xades.SelectSingleNode(@"//ds:KeyInfo/ds:X509Data/ds:X509Certificate", namespaceId); if (checkData == null) { return("neobsahuje element ds:X509Data"); } byte[] signatureCertificate = Convert.FromBase64String(xades.SelectSingleNode(@"//ds:KeyInfo/ds:X509Data/ds:X509Certificate", namespaceId).InnerText); byte[] signature = Convert.FromBase64String(xades.SelectSingleNode(@"//ds:SignatureValue", namespaceId).InnerText); XmlNode signedInfoNnn = xades.SelectSingleNode(@"//ds:SignedInfo", namespaceId); string signedInfoTransformAlg = xades.SelectSingleNode(@"//ds:SignedInfo/ds:CanonicalizationMethod", namespaceId).Attributes.GetNamedItem("Algorithm").Value; string signedInfoSignatureAlg = xades.SelectSingleNode(@"//ds:SignedInfo/ds:SignatureMethod", namespaceId).Attributes.GetNamedItem("Algorithm").Value; XmlDsigC14NTransform t1 = new XmlDsigC14NTransform(false); XmlDocument pom = new XmlDocument(); pom.LoadXml(signedInfoNnn.OuterXml); t1.LoadInput(pom); byte[] data = ((MemoryStream)t1.GetOutput()).ToArray(); string errMsg = ""; bool res = this.verifySign(signatureCertificate, signature, data, signedInfoSignatureAlg, out errMsg); if (!res) { Console.WriteLine("Error " + errMsg); return(errMsg); } //check Id in ds:Signature XmlNode dsSignatureId = xades.SelectSingleNode("//ds:Signature", namespaceId).Attributes["Id"]; if (dsSignatureId == null) { return("ds:Signature nemá atribút Id"); } //check namespace in ds:Signature XmlNode dsSignatureXmlns = xades.SelectSingleNode("//ds:Signature", namespaceId).Attributes["xmlns:ds"]; if (dsSignatureXmlns == null) { return("ds:Signature nemá špecifikovaný namespace xmlns:ds"); } //check SignatureValue Id XmlNode dsSignatureValueId = xades.SelectSingleNode("//ds:SignatureValue", namespaceId).Attributes["Id"]; if (dsSignatureValueId == null) { return("ds:SignatureValue nemá atribút Id"); } //check reference in ds:SignedInfo XmlNode signedInfo = xades.SelectSingleNode("//ds:SignedInfo", namespaceId); XmlNodeList dsKeyInfoId = signedInfo.SelectNodes("//ds:Reference", namespaceId); if (dsKeyInfoId.Count < 1) { return("ds:SignedInfo neobsahuje ds:Reference"); } String KeyInfo = ""; String SignatureProperties = ""; String SignedProperties = ""; List <string> Manifest = new List <string>(); //get URI foreach (XmlNode ReferenceList in dsKeyInfoId) { if (ReferenceList.Attributes["Id"] == null) { continue; } else if (ReferenceList.Attributes["Id"] != null) { if (ReferenceList.Attributes["Type"].Value.Contains("Object")) { KeyInfo = ReferenceList.Attributes["URI"].Value; KeyInfo = KeyInfo.Substring(1); } else if (ReferenceList.Attributes["Type"].Value.Contains("SignatureProperties")) { SignatureProperties = ReferenceList.Attributes["URI"].Value; SignatureProperties = SignatureProperties.Substring(1); } else if (ReferenceList.Attributes["Type"].Value.Contains("SignedProperties")) { SignedProperties = ReferenceList.Attributes["URI"].Value; SignedProperties = SignedProperties.Substring(1); } else if (ReferenceList.Attributes["Type"].Value.Contains("Manifest")) { String tmp = ReferenceList.Attributes["URI"].Value; tmp = tmp.Substring(1); Manifest.Add(tmp); } } } //check if exist ds:KeyInfo, ds:SignatureProperties, xades:SignedProperties XmlNode ElementKeyInfo = xades.SelectSingleNode("//ds:KeyInfo", namespaceId); XmlNode ElementSignatureProperties = xades.SelectSingleNode("//ds:SignatureProperties", namespaceId); XmlNode ElementSignedProperties = xades.SelectSingleNode("//xades:SignedProperties", namespaceId); if (ElementKeyInfo.Attributes["Id"] == null) { return("ds:Keyinfo nemá atribút Id"); } if (!ElementKeyInfo.Attributes["Id"].Value.Equals(KeyInfo)) { return("ds:Keyinfo, nezhoduje sa Id s URI"); } if (ElementSignatureProperties.Attributes["Id"] == null) { return("ds:SignatureProperties nemá atribút Id"); } if (!ElementSignatureProperties.Attributes["Id"].Value.Equals(SignatureProperties)) { return("ds:SignatureProperties, nezhoduje sa Id s URI"); } if (ElementSignedProperties.Attributes["Id"] == null) { return("xades:SignedProperties nemá atribút Id"); } if (!ElementSignedProperties.Attributes["Id"].Value.Equals(SignedProperties)) { return("xades:SignedProperties, nezhoduje sa Id s URI"); } //check if exist ds:Manifest XmlNodeList ElementManifest = xades.SelectNodes("//ds:Manifest", namespaceId); bool flag = false; foreach (XmlNode OneManifest in ElementManifest) { foreach (String ManifestURI in Manifest) { if (OneManifest.Attributes["Id"] == null || !OneManifest.Attributes["Id"].Value.Equals(ManifestURI)) { flag = true; } } } if (!flag) { return("ds:Manifest nemá atribút Id alebo sa nezhoduje Id s URI"); } //check ds:KeyInfo Id if (ElementKeyInfo.Attributes["Id"] == null) { return("element ds:KeyInfo nemá atribút Id"); } //check ds:KeyInfo elements XmlNode X509Data = ElementKeyInfo.SelectSingleNode("//ds:X509Data", namespaceId); if (X509Data == null) { return("ds:KeyInfo neobsahuje element ds:X509Data"); } if (X509Data.ChildNodes.Count < 3) { return(" chýbajú podelementy pre ds:X509Data"); } //check ds:KeyInfo values XmlNodeList elemList = X509Data.ChildNodes; byte[] bytes; var cert = new X509Certificate2(); String IssuerSerialFirst = ""; String IssuerSerialSecond = ""; String SubjectName = ""; for (int i = 0; i < elemList.Count; i++) { switch (elemList[i].Name) { case "ds:X509Certificate": bytes = Convert.FromBase64String(elemList[i].InnerText); cert = new X509Certificate2(bytes); break; case "ds:X509IssuerSerial": if (elemList[i].HasChildNodes) { IssuerSerialFirst = elemList[i].FirstChild.InnerText; IssuerSerialSecond = elemList[i].LastChild.InnerText; } break; case "ds:X509SubjectName": SubjectName = elemList[i].InnerText; break; } } BigInteger hex = BigInteger.Parse(cert.SerialNumber, NumberStyles.AllowHexSpecifier); if (!cert.Subject.Equals(SubjectName)) { return("hodnota ds:X509SubjectName sa nezhoduje s príslušnou hodnotou v certifikáte"); } if (!cert.Issuer.Equals(IssuerSerialFirst)) { return("hodnota ds:X509IssuerName sa nezhoduje s príslušnou hodnotou v certifikáte"); } if (!hex.ToString().Equals(IssuerSerialSecond)) { return("hodnota ds:X509SerialNumber sa nezhoduje s príslušnou hodnotou v certifikáte"); } //check ds:SignatureProperties Id if (ElementSignatureProperties.Attributes["Id"] == null) { return("element ds:SignatureProperties nema atribut Id"); } //check ds:SignatureProperties numbers of elements XmlNodeList elemListSignatureProperties = ElementSignatureProperties.ChildNodes; if (elemListSignatureProperties.Count < 2) { return("ds:SignatureProperties neobsahuje dva elementy"); } //check ds:SignatureProperties elements for (int i = 0; i < elemListSignatureProperties.Count; i++) { if (elemListSignatureProperties[i].FirstChild.Name.Equals("xzep:SignatureVersion") || elemListSignatureProperties[i].FirstChild.Name.Equals("xzep:ProductInfos")) { String tmpTargetValue = elemListSignatureProperties[i].Attributes["Target"].Value; tmpTargetValue = tmpTargetValue.Substring(1); if (!tmpTargetValue.Equals(dsSignatureId.Value)) { return("atribút Target v elemente ds:SignatureProperty nie je nastavený na element ds:Signature"); } } } //check Manifest and Manifest references String ManifestReferenceUri = ""; String algorithmDigestMethod = ""; String algorithmTransforms = ""; String digestValue = ""; bool flag1 = false; for (int i = 0; i < ElementManifest.Count; i++) { //check ds:Manifest Id if (ElementManifest[i].Attributes["Id"] == null) { return("jeden z elementov ds:Manifest nemá atribút Id"); } //check number of reference, ds:Object XmlNodeList ManifestChildNodes = ElementManifest[i].ChildNodes; if (ManifestChildNodes.Count > 1 || ManifestChildNodes.Count < 1) { return("ds:Manifest neobsahuje práve jedenu referenciu"); } if (!ManifestChildNodes[0].Attributes["Type"].Value.Contains("Object")) { return("nezhoduje sa Type v ds:Manifest"); } //check value attribute Type if (ManifestChildNodes[0].Attributes["Type"].Value.Equals("http://www.w3.org/2000/09/xmldsig#Object")) { //check supported ds:Transforms and ds:DigestMethod XmlNodeList ReferenceElementsChild = ManifestChildNodes[0].ChildNodes; for (int l = 0; l < ReferenceElementsChild.Count; l++) { if (ReferenceElementsChild[l].Name.Equals("ds:Transforms")) { algorithmTransforms = ReferenceElementsChild[l].FirstChild.Attributes["Algorithm"].Value; if (!SUPPORTED_TRANSFORMS.Contains(algorithmTransforms)) { return("ds:Transforms neobsahuje podporovaný algoritmus pre daný element podľa profilu XAdES_ZEP"); } } if (ReferenceElementsChild[l].Name.Equals("ds:DigestMethod")) { algorithmDigestMethod = ReferenceElementsChild[l].Attributes["Algorithm"].Value; if (!SUPPORTED_DIGEST_METHOD.Contains(algorithmDigestMethod)) { return("ds:DigestMethod neobsahuje podporovaný algoritmus pre daný element podľa profilu XAdES_ZEP"); } } if (ReferenceElementsChild[l].Name.Equals("ds:DigestValue")) { digestValue = ReferenceElementsChild[l].InnerText; } } ManifestReferenceUri = ManifestChildNodes[0].Attributes["URI"].Value; ManifestReferenceUri = ManifestReferenceUri.Substring(1); //check values ds:Manifest and ds:Object XmlNodeList ObjectElement = xades.SelectNodes("//ds:Object", namespaceId); for (int j = 0; j < ObjectElement.Count; j++) { if (ObjectElement[j].Attributes["Id"] == null) { continue; } if (ObjectElement[j].Attributes["Id"].Value.Equals(ManifestReferenceUri)) { flag1 = true; XmlDsigC14NTransform t = new XmlDsigC14NTransform(); XmlDocument myDoc = new XmlDocument(); myDoc.LoadXml(ObjectElement[i].OuterXml); t.LoadInput(myDoc); Stream s = (Stream)t.GetOutput(typeof(Stream)); byte[] hash; string base64String = ""; switch (algorithmDigestMethod) { case "http://www.w3.org/2001/04/xmldsig#sha1": SHA1 sha1 = SHA1.Create(); hash = sha1.ComputeHash(s); base64String = Convert.ToBase64String(hash); break; case "http://www.w3.org/2001/04/xmlenc#sha256": SHA256 sha256 = SHA256.Create(); hash = sha256.ComputeHash(s); base64String = Convert.ToBase64String(hash); break; case "http://www.w3.org/2001/04/xmldsig-more#sha384": SHA384 sha384 = SHA384.Create(); hash = sha384.ComputeHash(s); base64String = Convert.ToBase64String(hash); break; case "http://www.w3.org/2001/04/xmlenc#sha512": SHA512 sha512 = SHA512.Create(); hash = sha512.ComputeHash(s); base64String = Convert.ToBase64String(hash); break; } Console.WriteLine("-"); Console.WriteLine("Overenie hodnoty ds:DigestValue"); Console.WriteLine("First " + base64String); Console.WriteLine("Second " + digestValue); Console.WriteLine("-"); } } if (!flag1) { return("odkaz z ds:Manifest na ds:Object sa nezhoduje"); } flag1 = false; } else { return("ds:Reference, hodnota atribútu Type sa neoverila voči profilu XADES_ZEP"); } } return("OK"); }